首页 > 解决方案 > 在 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();
    });
}

标签: databaselaraveleloquentcollectionscategorical-data

解决方案


我已经得到了答案我删除了关系并将位置添加到一个值以便 c


推荐阅读