我有3种型号:
class User extends Authenticatable
{
...
public function certifications()
{
return $this->belongsToMany('App\Certification', 'certification_user');
}
...
}
class Certification extends Model {
...
public function referential()
{
return $this->belongsTo('App\Referential');
}
...
}
class Referential extends Model
{
...
public function certifications()
{
return $this->hasMany('App\Certification');
}
...
}
我正在尝试获取当前用户认证的所有参考。 我可以做到:
App\User::with("certifications");
...然后进行迭代,但是我宁愿有Collection
个对象中的一个Referential
我认为我应该做类似的事情
App\Referential::whereHas("certifications", function($query){
// something like "where certification in User::certifications()"
});
但是我无法正常工作。
谢谢
答案 0 :(得分:0)
您可以使用嵌套的紧急加载:
$user = App\User::with('certifications.referential')->first();
$referentials = $user->certifications->pluck('referential');
whereHas()
查询如下:
App\Referential::whereHas('certifications.users', function($query) use($user) {
$query->where('users.id', $user->id);
});