是否可以将以下代码转换为一行?
// Fetch the producer role
$Roles = Role::where('label', '=', 'Producer')->get();
$role = $Roles->first();
// Fetch the producers
$Producers = Role::find($role->role_id)->users()->get();
这也是我的Pivot表逻辑的样子(在Role中):
public function users() {
return $this->belongsToMany('User', 'UsersRoles', 'role_id', 'user_id');
}
答案 0 :(得分:0)
是的,但你为什么要把它压成一条线?除了它是完全多余的..
// 1st query, load collection of roles...
$Roles = Role::where('label', '=', 'Producer')->get();
// ... just to use one of them?
$role = $Roles->first();
$Producers =
// run another query to get the same role...
Role::find($role->role_id)
->users()->get();
无论如何,这是一个单行:
$producers = Role::where('lable', 'Producer')->first()->users;
// or
$producers = Role::where('lable', 'Producer')->with('users')->first()->users;