【问题标题】:3 models in laravel 4 - select with relation whereHas Querylaravel 4 中的 3 个模型 - 选择关系 whereHas Query
【发布时间】:2015-03-27 10:36:53
【问题描述】:

我有 3 个模型:

  • 用户
  • 星球
  • 太阳系

关系:

在用户模型中:

    public function planets() {
        return $this->hasMany('Planet');
    }

在行星模型中:

    public function sunsystem() {
        return $this->belongsTo('Sunsystem');
    }

    public function user() {
        return $this->belongsTo('User');
    }

在太阳系模型中:

    public function planets() {
        return $this->hasMany('Planet');
    }

现在我想选择所有相关行星的所有太阳系 但只有相关行星属于实际用户的太阳系(在此示例中为 ID 12)。 但是我如何得到正确的结果? 这是我尝试的,但它只给了我一个太阳系统,但我希望有 2 个太阳系统。我认为我的查询是错误的...:

        $s = Sunsystem::whereHas('Planets', function($q) {
            $q->whereHas('User', function ($u) {
                $u->whereUserId(12);
            });
        })->get();

这也行不通:

     $s = Sunsystem::select('Sunsystems.*')
       ->join('planets','planets.sunsystem_id','=','sunsystems.id')
       ->join('users','users.id','=','planets.user_id')
       ->where('users.id','=',12)
       ->get();

如果有 2 个行星具有不同的 sunsystem_id 但相同的 user_id,我只会得到一个 sunsystem,但我希望有两个。

【问题讨论】:

    标签: php mysql laravel relationship


    【解决方案1】:

    请试一试

    $s = Sunsystem::select('Sunsystems.*')
         ->join('planets','planets.sunsystem_id','=','Sunsystems.id')
         ->join('users','users.id','=','planets.user_id')
         ->where('users.id','=',12)
         ->get();
    

    【讨论】:

    • 不.. 不起作用。如果有 2 个行星具有不同的 sunsystem_id 但相同的 user_id 我只得到一个太阳系,但我希望有两个。
    猜你喜欢
    • 2014-06-01
    • 2018-12-07
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 2018-10-17
    • 2014-11-29
    • 2023-03-09
    • 1970-01-01
    相关资源
    最近更新 更多