问题
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