我有一个与用户有这种关系的帖子模型:
public function author()
{
return $this->belongsTo(User::class, 'user_id');
}
我正在构建搜索功能,我有这段代码
public function index(Request $request)
{
$search = $request->search;
$filter = $request->filter;
$append = array();
$posts = Post::with('author')->with('categories')->latest();
if($search){
switch ($filter) {
case 'username':
$posts->author->where('username', 'LIKE', '%'. $search . '%');
break;
}
$append += array('search' => $search);
$append += array('filter' => $filter);
}
$posts = $posts->paginate(3);
$posts->appends($append);
return view('core.blog.posts.index', compact('posts'));
}
我得到了
未定义的属性:Illuminate \ Database \ Eloquent \ Builder :: $ author
如何根据用户名添加查找作者的位置?我必须能够在if case
中添加这个条件答案 0 :(得分:1)
<强>更新强>
如果您需要有条件的地方,可以这样做:
$postSelector = Post::with('categories');
if($search){
switch ($filter) {
case 'username':
$postSelector->with(['author' => function($q) use($search) {
$q->where('username', 'LIKE', '%'. $search . '%');
}]);
break;
}
$posts = $postSelector->get();
答案 1 :(得分:1)
您想要whereHas()
使用searched based on a relation。这将只返回作者具有用户名的帖子。
switch ($filter) {
case 'username':
$posts->whereHas('author', function($q) use($search) {
$q->where('username', 'LIKE', '%'. $search . '%');
});
break;
}