我有 3 个模型:
- 用户
- 行星
- 太阳系统
关系:
在用户模型中:
public function planets() {
return $this->hasMany('Planet');
}
在行星模型中:
public function sunsystem() {
return $this->belongsTo('Sunsystem');
}
public function user() {
return $this->belongsTo('User');
}
在sunsystem模型中:
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,但我希望有两个。
最佳答案
请尝试一下
$s = Sunsystem::select('Sunsystems.*')
->join('planets','planets.sunsystem_id','=','Sunsystems.id')
->join('users','users.id','=','planets.user_id')
->where('users.id','=',12)
->get();
关于php - laravel 4 中的 3 个模型 - 通过关系 whereHas 查询进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29298666/