类别别名 + post 别名 Laravel Eloquent

Category slug + post slug Laravel Eloquent

我有一个博客路线,我想显示带有 category_slug 的文章。

Route::get('/blog/{category_slug}/{slug}', [App\Http\Controllers\BlogController::class, 'index'])
       ->where('category_slug', '[\-_A-Za-z]+')
       ->where('slug', '[\-_A-Za-z]+');


public function categories_blog()
{
    return $this->belongsTo(CategoriesBlog::class, 'category_id');
}

public function blogs()
{
    return $this->hasMany(Blog::class);
}

与此 eloquent 关系正常工作:

示例:www.mysite.com/blog/first_article

public function index($category_slug, $slug)
{

$blogs = Blog::with('categories_blog')
               ->where('slug', '=', $slug)
               ->first();

}

这个 eloquent 关系不起作用:

示例:www.mysite.com/blog/accessories/first_article

public function index($category_slug, $slug)
{

$blogs = Blog::with('categories_blog')
             ->where('category_slug', '=', $category_slug)
             ->where('slug', '=', $slug)
             ->first();  

}

无法识别与 'categories blogs' 的关系:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'category_slug' in 'where clause' (SQL: select * from `blogs` where `category_slug` = accessories `slug` = first_article limit 1)

我该如何修复它,或者有没有最好的方法来解决这个问题? 非常感谢。

使用 whereHas

$blogs = Blog::with('categories_blog')->whereHas('categories_blog',function ($query)use($category_slug){
           $query ->where('category_slug', $category_slug);
       })
          ->where('slug',$slug)
          ->first();