首页 > 解决方案 > 3表多对多关系

问题描述

我在 Laravel 中创建一个网站并遇到了以下问题。

我有三个表:UserJobOfferCompany 许多用户有很多工作机会。

我在用户和 Joboffers 之间创建了多对多关系。

用户型号:

return $this->belongsToMany('App\JobOffer')->withTimestamps();

工作机会模型:

return $this->belongsToMany('App\User')->withTimestamps();

但问题是 Joboffers 表有一列company_id(因为 Company 和 Joboffer 之间的关系),而 Users-Joboffer 之间的关系返回的是公司的 id。但我想知道公司的名称。

非常感谢!

更新

我的模型:

应用\用户.php

public function job_offers()
{
    return $this->belongsToMany('App\JobOffer')->withTimestamps();
}

应用\JobOffer.php

public function users()
{
    return $this->belongsToMany('App\User')->withTimestamps();
}

public function company()
{
    return $this->belongsTo('App\Company');
}

应用\公司.php

public function job_offers()
{
    return $this->hasMany('App\JobOffer');
}

用户IGP是对的。非常感谢 IGP。

标签: phplaraveleloquentpivotmany-to-many

解决方案


在提供更多细节之前,我假设关系如下:

  • User模型和JobOffer模型具有 M:N 关系
  • Company模型和JobOffer模型具有 1:M 的关系
# App\User.php
public function job_offers()
{
    return $this->belongsToMany('App\JobOffer')->withTimestamps();
}
# App\JobOffer.php
public function users()
{
    return $this->belongsToMany('App\User')->withTimestamps();
}

public function company()
{
    return $this->belongsTo('App\Company');
}
# App\Company.php
public function job_offers()
{
    return $this->hasMany('App\JobOffer');
}

从这些关系中,您可以像这样获得公司名称:

use App\User;

$user = User::with('job_offers.company')->where(...)->first();

生成的对象将如下所示:

App\User {
  id: 1,
  created_at: "",
  updated_at: "",
  job_offers: Illuminate\Database\Eloquent\Collection {
    all: [
      App\JobOffer {
        id: 85,
        company_id: 36,
        created_at: "",
        updated_at: "",
        pivot: Illuminate\Database\Eloquent\Relations\Pivot {
          job_offer_id: 85,
          user_id: 1,
          created_at: "",
          updated_at: "",
        },
        company: App\Company {
          id: 36,
          name: "Company1"
          created_at: "",
          updated_at: "",
        },
      },
      App\JobOffer {
        id: 90,
        company_id: 44,
        created_at: "",
        updated_at: "",
        pivot: Illuminate\Database\Eloquent\Relations\Pivot {
          job_offer_id: 90,
          user_id: 1,
          created_at: "",
          updated_at: "",
        },
        company: App\Company {
          id: 44,
          name: "Company2"
          created_at: "",
          updated_at: "",
        },
      },
    ],
  },
}

您需要做的就是遍历用户的工作机会以获取每个公司的名称。

@foreach($user->job_offers as $job_offer)
    Company name: {{ $job_offer->company->name }}
@endforeach

推荐阅读