1 回答

TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超11個(gè)贊
在提供更多細(xì)節(jié)之前,我假設(shè)關(guān)系如下:
用戶模型和JobOffer模型具有 M:N 關(guān)系
公司模型和JobOffer模型具有 1:M 關(guān)系
# 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');
}
從這些關(guān)系中,您可以像這樣獲得公司名稱:
use App\User;
$user = User::with('job_offers.company')->where(...)->first();
生成的對(duì)象將如下所示:
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: "",
},
},
],
},
}
您需要做的就是遍歷用戶的工作機(jī)會(huì)以獲取每個(gè)公司名稱。
@foreach($user->job_offers as $job_offer)
Company name: {{ $job_offer->company->name }}
@endforeach
- 1 回答
- 0 關(guān)注
- 183 瀏覽
添加回答
舉報(bào)