1 回答
TA贡献1856条经验 获得超11个赞
在提供更多细节之前,我假设关系如下:
用户模型和JobOffer模型具有 M:N 关系
公司模型和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
- 1 回答
- 0 关注
- 163 浏览
添加回答
举报