【问题标题】:Category slug + post slug Laravel Eloquent分类 slug + post slug Laravel Eloquent
【发布时间】:2021-09-21 11:19:59
【问题描述】:

我有一条博客路线,我想展示带有 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);
}

这种雄辩的关系可以很好地工作:

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

public function index($category_slug, $slug)
{

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

}

这种雄辩的关系是行不通的:

示例: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();  

}

无法识别与“类别博客”的关系:

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)

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

【问题讨论】:

    标签: laravel eloquent relationship


    【解决方案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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-04
      • 2018-03-28
      • 2018-09-13
      • 2019-04-19
      • 2014-02-17
      • 1970-01-01
      • 2020-10-02
      • 2016-09-13
      相关资源
      最近更新 更多