I have two tables. Like this
**
user_accounts usersonglists
-------------- ---------------
id id
username user_account_id
slug etc..
etc..
** I created a route like this
/u/{slug}/songlists
This relation method in songlist model
public function userAccounts()
{
return $this->belongsTo('App\Models\User\UserAccounts','user_account_id','id');
}
I created controller method like this
$songLists = $SongListRepository->getSongListsByUserSlug($slug);
This is getSongListByUserSlug($slug) method
$songList = $this->model->with('userAccounts')->get();
I want to get songlists by user with $slug.
Can someone help me?
You're looking for the whereHas
method:
$query = $this->model->with('userAccounts');
$query->whereHas('userAccounts', function($query) use ($slug) {
$query->where('slug', $slug);
})
$lists = $query->get();
BTW, you should probably rename that userAccounts
method to the singular userAccount
.
An easier way might be to start from the account:
$lists = UserAccount::where('slug', $slug)->songLists;
Assuming you've set up the inverse relationship.