我有了這種關係給用戶一個職位模型的帖子:
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'));
}
我得到
未定義屬性:照亮\數據庫\雄辯\ ::生成筆者$
如何根據用戶名添加作者的位置?
$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();
謝謝你,你的解決方案是完美的,因爲我不想修改這一行:$ posts = Post :: with('author') - > with('categories') - > latest();作爲其他答案。 –