分类 slug + post slug Laravel Eloquent
Posted
技术标签:
【中文标题】分类 slug + post slug Laravel Eloquent【英文标题】:Category 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)
我该如何解决它,或者有没有最好的方法来解决这个问题? 非常感谢。
【问题讨论】:
【参考方案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();
【讨论】:
以上是关于分类 slug + post slug Laravel Eloquent的主要内容,如果未能解决你的问题,请参考以下文章
Wordpress // 删除 URL 的帖子类型 slug