一個是產品中的另一個是提供
products
---------
id | offer_id
offers
---------
id | product_id
現在我想所有優惠對產品
在我的產品型號我寫
public function getOfferDetails()
{
return $this->belongsTo('App\Offer');
}
但它返回null。
一個是產品中的另一個是提供
products
---------
id | offer_id
offers
---------
id | product_id
現在我想所有優惠對產品
在我的產品型號我寫
public function getOfferDetails()
{
return $this->belongsTo('App\Offer');
}
但它返回null。
你想得到屬於product
的所有offers
,對不對?你有沒有試過這個:
public function getOfferDetails()
{
return $this->hasMany('App\Offer');
}
在你的Product
模型?
需要定義您的關係如何。基於你有什麼
一個產品可以有0 - 許多優惠和一個優惠屬於1產品。
您將需要一些外鍵來匹配模型。 OTB Laravel將嘗試使用附加_id作爲外鍵的方法名稱。由於您的方法名稱不同,因此您需要將外鍵作爲關係方法中的第二個參數傳遞。
產品型號應該有
public function getOfferDetails()
{
return $this->hasMany('App\Offer', 'product_id');
}
發售型號應該有
public function getProduct()
{
return $this->belongsTo('App\Product', 'product_id');
}
Laravel Documentation可能幫助了爲好。
這是你在找什麼,我認爲:
public function getOfferDetails()
{
return $this->hasMany('App\Offer', 'id', 'offer_id');
// as ceejayoz mentioned in comments, Laravel should be able to detect this themselves. The below would work the exact same as above
// return $this->hasMany('App\Offer', 'id', 'offer_id')
}
$product->getOfferDetails()->get();
如果表和字段是按Laravel文檔命名的(它們看起來像),那麼額外的參數是不必要的。 – ceejayoz
謝謝,你說的沒錯。 –
好,還有在報價表綁在該產品的所有優惠? – ceejayoz
順便說一下,'products'表通常不應該有'offer_id'列。 – ceejayoz