Eager Load Constraints Filter issue in Laravel

2019-02-19 18:23发布

问题:

I am unable to filter the contents of groups table with respect to username in users table using Eager Load Constraints

public function username()
{
    return $this->belongsTo('User','fk_users_id')->select(['id','username']);
}

I have tried using the code below but it filters only the users data not the groups data

$groups     =   Groups::with(array('username' => function($query) use ($keyword)
                                                        {
                                                            $query->where('username', 'like', '%'.$keyword.'%');

                                                        }))
                ->where('status',1)->paginate($paginateValue);

any help is welcome...

回答1:

Think it should be something like this:

Groups::with('User')->whereHas('User', function($q) use ($key){
 $q->where('username', 'like', '%'.$key.'%');
})->where('status', 1)->paginate($pagVal);