database - 在 HomeController (Laravel 8) 中按类别名称获取帖子
问题描述
详细解释一下:例如,我正在创建带有类别的帖子,但是我将其保存在不同的表(post_categories)中,这意味着我的帖子和类别通过它们的 ID 连接(belongToMany)。现在在我的 HomeController 中,我想按类别名称显示帖子,例如: $posts = post::where([['status',1],['category', 'electronics'])->orderBy('created_at', 'DESC')->limit(1)->get();
我想按类别名称而不是类别 ID 显示我的帖子
我试过了,但它并没有真正起作用,我想我忘记了什么或者我使用了错误的方法,请帮助我
代码
家庭控制器
public function index()
{
$posts = post::where([['status',1],//here is category missing])->orderBy('created_at', 'DESC')->limit(1)->get();
$categories = Category::all();
return view('user.home', compact('posts', 'categories'));
}
public function category(category $category)
{
$posts = $category->posts();
return view('user.home',compact('posts'));
}
类别 型号
use HasFactory;
public function posts()
{
return $this->belongsToMany('App\Models\user\post','category_posts')->orderBy('created_at','DESC')->paginate(5);
}
public function getRouteKeyName()
{
return 'slug';
}
后模型
use HasFactory;
public function categories()
{
return $this->belongsToMany('App\Models\user\category','category_posts')->withTimestamps();;
}
public function getRouteKeyName()
{
return 'slug';
}
数据库
Posts_table
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title',1000);
$table->string('subtitle',1000);
$table->string('slug',1000)->nullable();
$table->text('body');
$table->boolean('status')->nullable();
$table->integer('posted_by')->nullable();
$table->string('image')->nullable();
$table->timestamps();
});
}
分类表
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug');
$table->timestamps();
});
}
category_posts
public function up()
{
Schema::create('category_posts', function (Blueprint $table) {
$table->unsignedBigInteger('post_id');
$table->unsignedInteger('category_id');
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->timestamps();
});
}
解决方案
我已经得到了答案我删除了关系并将位置添加到一个值以便 c
推荐阅读
- python-3.x - 如何根据其他列python中的值变化提取列的值
- c++ - 使用指定路径从目录加载 PCD 文件(路径包含作为文件名的字符串)
- git - 在提交详细信息中搜索 Bitbucket 存储库中的评论
- swift - 获取视频数组的缩略图
- visual-studio-code - 并行安装 Visual Studio Code (vscode) 和 Visual Studio Code Insiders (vscode Insiders):修改标准应用
- import - 边缘数据未完全加载到 Neptune(通过 Python 和 Gremlin)
- codeigniter-3 - 我可以在 CodeIgniter Controller 中编写单个方法来处理 GET 和 POST 登录表单吗?
- c# - 如何根据租户动态更改资源路径(我们根据主机名确定租户)?
- java - 如何使用 cassandra java 驱动程序(3.6 版)在 Cassandra 访问器接口中传递分页状态?
- angular - 找不到名称“许多”-升级到 TypeScript 3.1.6