[英]How to select article by category name with Laravel Eloquent
我對如何使用 laravel eloquent 按類別名稱進行 select 文章有疑問。 我在 controller 中的索引 function:
$article = Article::with('category')->when(request()->q, function($article) {
$article->where('category.name', 'like', '%'. request()->q . '%');
})->latest()->paginate(10);
此代碼返回錯誤:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'category.name' in 'where clause'
我的文章 model 已設置為屬於類別
public function category()
{
return $this->belongsTo(Category::class,"category_id");
}
但我並不奇怪它仍然無法正常工作。 謝謝你的幫助。
$article = Article::with('category')
->when(request()->q, function($article) {
$article->whereHas('category',
fn($q) => $q->where('name', 'like', '%'. request()->q . '%')
);
})
->latest()
->paginate(10);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.