2016-06-10 110 views
0

我有两个表Laravel Relaton返回null

一个是产品中的另一个是提供

products 
--------- 
id | offer_id 

offers 
--------- 
id | product_id 

现在我想所有优惠对产品

在我的产品型号我写

public function getOfferDetails() 
{ 
    return $this->belongsTo('App\Offer'); 
} 

但它返回null。

+0

好,还有在报价表绑在该产品的所有优惠? – ceejayoz

+0

顺便说一下,'products'表通常不应该有'offer_id'列。 – ceejayoz

回答

0

你想得到属于product的所有offers,对不对?你有没有试过这个:

public function getOfferDetails() 
{ 
    return $this->hasMany('App\Offer'); 
} 

在你的Product模型?

0

需要定义您的关系如何。基于你有什么

一个产品可以有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可能帮助了为好。

0

这是你在找什么,我认为:

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(); 
+1

如果表和字段是按Laravel文档命名的(它们看起来像),那么额外的参数是不必要的。 – ceejayoz

+1

谢谢,你说的没错。 –