我有两张桌子。像这样
**
user_accounts usersonglists
-------------- ---------------
id id
username user_account_id
slug etc..
etc..
**我创建了这样的路线
/u/{slug}/songlists
歌曲列表模型中的此关联方法
public function userAccounts()
{
return $this->belongsTo('App\Models\User\UserAccounts','user_account_id','id');
}
我创建了这样的控制器方法
$songLists = $SongListRepository->getSongListsByUserSlug($slug);
这是getSongListByUserSlug($ slug)方法
$songList = $this->model->with('userAccounts')->get();
我想用$ slug按用户获取歌曲列表。
有人能帮我吗?
您正在寻找的whereHas
方法:
$query = $this->model->with('userAccounts');
$query->whereHas('userAccounts', function($query) use ($slug) {
$query->where('slug', $slug);
})
$lists = $query->get();
顺便说一句,您可能应该将该userAccounts
方法重命名为singular userAccount
。
一个更简单的方法可能是从帐户开始:
$lists = UserAccount::where('slug', $slug)->songLists;
假设您已经建立了逆关系。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句