1
考慮以下數據庫方案獲得屬於關聯:Laravel通過中間表
companies
-- id
-- name
logos
-- id
-- active
-- company_id
-- image_id
images
-- id
-- filename
-- path
-- type
然後,我在模型關係定義是這樣的:
Company.php
public function logos() {
return $this->hasMany('App\Models\Logo');
}
標誌.php
public function image() {
$this->belongsTo('App\Models\Image');
}
現在我想要根據其標識和圖像得到具體的公司。於是,我就這樣把它拿來,但它引發錯誤:
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
CompanyController.php
public function show($id) {
$company = Company::findOrFail($id);
$requester = JWTAuth::parseToken()->toUser();
if(!$requester->hasRole('noc') && $requester->company_id != $company->id) {
return $this->response->errorUnauthorized("You have no rights to view this company profile.");
}
// I am trying to fetch it this way //
$company->logos;
foreach ($company->logos as $logo) {
return $logo->image;
}
return $this->response->array(compact('company'))->setStatusCode(200);
}
誰能幫助我? :) 謝謝!
不起作用,拋出:'上null' – user3216673
那是因爲你已經忘了return'加上'的'image'關係調用一個成員函數addEagerConstraints() 。 –
:D是的,我是noob!謝謝:),我會在6分鐘內接受你的回答:) – user3216673