简体   繁体   English

Laravel 从多对多关系中获取关系

[英]Laravel get relations from a many to many relations

I have 3 models: User , Company and Vacancie .我有 3 个模型: UserCompanyVacancie

The Models have the following relations:模型具有以下关系:

User many to many Company用户many to many公司

Company one to many Vacancie公司one to many空缺

How can I get all Vacancie a User has access to?如何获得User有权访问的所有Vacancie

I've found this answer but auth()->user()->with('companies.vacancies')->get();我找到了这个答案,但是auth()->user()->with('companies.vacancies')->get(); returns all users of my database.返回我的数据库的所有用户。

You can do something like this:你可以这样做:

$userId = $request->user_id;
$vacancies = Vacancie::whereHas('companies', function ($q) use ($userId){
    $q->whereHas('users', function($q1) use ($userId) {
        $q1->where('users.id', userId);
    });
})->get();

In this code, I'm considering that you have the relations companies() in Vacancie and users() in Company .在此代码中,我考虑您在Vacancie拥有关系companies()和在Company users()

This will do the inverse of what you are doing now.这将与您现在所做的相反。 When you call get() in the user model, you will get all the users with the relations pré-loaded ( with() ).当您在用户模型中调用get()时,您将获得所有具有预加载关系的用户( with() )。

Create a vacancies relationship on the User model as follows:User模型上创建一个vacancies关系,如下所示:

//inside the User model
public function vacancies()
    {
        $vacancies= new Illuminate\Database\Eloquent\Collection;

        foreach($this->companies as $company)
        {
            $vacancies = $vacancies->merge($company->vacancies->get());
        }

        return $vacancies->unique();
    }

Then you can do auth()->user()->with('vacancies')->get() .然后你可以做auth()->user()->with('vacancies')->get() Not tested, but the general idea holds.未经测试,但总体思路成立。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM