php - 3表多对多关系
问题描述
我在 Laravel 中创建一个网站并遇到了以下问题。
我有三个表:User、JobOffer和Company 许多用户有很多工作机会。
我在用户和 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。
解决方案
在提供更多细节之前,我假设关系如下:
- 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
推荐阅读
- python-requests - 当 URL 不存在时,为什么“请求”不返回 404?
- reactjs - 状态更新时不会触发useEffect
- gsm - SIM800L : AT+HTTPACTION:601 网络错误
- footer - 将另一个图像插入到 footer.php
- python - 我正在学习 python,请有人告诉我如何修复它,这样我就可以慢慢打印每个字母(就像打字机一样),但也可以使用输入
- python - python Binance:APIError(code = -1013):过滤器失败:LOT_SIZE
- c++ - 在 C++ 程序中获得超出输出限制
- python - CUDA_ERROR_ILLEGAL_ADDRESS - 在训练 tensorflow keras 模型时
- amazon-redshift - 我们可以在 Redshift 中使用 CTE(with 子句)进行 UPDATE 查询吗?
- spring-cloud-stream - 如何在消费者中获取消息标头