无法让这个雄辩的查询工作

时间:2017-10-31 19:50:01

标签: laravel eloquent laravel-5.4

我正在尝试从UserGroup模型和组模型中获取值(UserGroup中的belongsTo方法)

在UserGroup模型中:

public function group()
    {
        return $this->belongsTo('App\Models\Group', 'group_id', 'group_id');
    }

我的查询:

$arrayGroupes = UserGroup::from("user_group as ug")
->with( ['group' => function($query){
    $query->select('group_id','name as name_group', DB::raw("IF(restricted=1,1,0) as restricted"), "transfer_only");
}])->select("ug.user_id", "u.first_name", "u.surname")
   ->join("users as u", "u.user_id", "=", "ug.user_id")
   ->whereIn("ug.group_id", [1,2,3,4,5])
   ->where("ug.active", "=", 1)->get();

返回null 但如果只做

$arrayGroupes = UserGroup::with( ['group' => function($query){
        $query->select('group_id','name as name_group', DB::raw("IF(restricted=1,1,0) as restricted"), "transfer_only");
    }])->whereIn("group_id", [1,2,3,4,5])
       ->where("active", "=", 1)->get();

它可以工作,但不能只从UserGroup中选择一些值... 有人作为我的答案吗? 谢谢!

1 个答案:

答案 0 :(得分:1)

$userGroups = UserGroup::from("user_group as ug")
    ->join("users as u", "u.user_id", "=", "ug.user_id")
    ->select("ug.user_id", "ug.group_id", "ug.active", "u.first_name", "u.surname")
    ->with( ['group' => function($query){
        $query->select('group_id','name as name_group', DB::raw("IF(restricted=1,1,0) as restricted"), "transfer_only");
    }])
    ->whereIn("ug.group_id", [1,2,3,4,5])
    ->where("ug.active", "=", 1)
    ->get();

试一试。未经测试。