Laravel 5 关系
Laravel 5 relationships
我有两张桌子。像这样
**
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
方法重命名为单数 userAccount
.
更简单的方法可能是从帐户开始:
$lists = UserAccount::where('slug', $slug)->songLists;
假设你已经建立了反向关系。
我有两张桌子。像这样
**
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
方法重命名为单数 userAccount
.
更简单的方法可能是从帐户开始:
$lists = UserAccount::where('slug', $slug)->songLists;
假设你已经建立了反向关系。