Eloquent query scope on relationship

我怕爱的太早我们不能终老 提交于 2020-06-13 05:58:29

问题


I have two models called Page and User and I've set up the Eloquent relation as follows:

public function user() {
  return $this->belongsTo('User')
}

When I dd(Page::with('user')->get()) I get the right result. But now I want to have a search filter on this result.

I've used a scopeSearch but I'm not sure how to search on the resultset.

At the moment I have a scope like this:

public function scopeSearch($query, $search) {
  $query->where('username', 'LIKE', '%'.$search.'%')
     ->orWhere('name', 'LIKE', '%'.$search.'%')
}

So when I Page::with('user')->search('Test')->get() it is not working. The problem (probably) is that the username column is part of the User table and the name is part of the Page table.

How would I be able to use a scope or something familiar, to search on the resultset, without repeating it in most of the queries?


回答1:


You need to create scopeSearch in User model and you should use it this way:

$posts = Page::with('user')->whereHas('user', function($q) use ($search)
{
    $q->search($search);

})->get();


来源:https://stackoverflow.com/questions/26978968/eloquent-query-scope-on-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!