雄辩的关系

时间:2018-08-23 12:53:11

标签: eloquent laravel-query-builder

我有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()"
});

但是我无法正常工作。

谢谢

1 个答案:

答案 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);
});