Laravel 4,如何访问反向一对多关系? [英] Laravel 4, how to access reverse one-to-many relation?
问题描述
代码:
<?php
class Catering extends \Eloquent {
protected $table = 'catering';
public $timestamps = FALSE;
public function offers() {
return $this->hasMany('Offer', 'cid');
}
}
class Offer extends \Eloquent {
protected $table = 'catering_offer';
public $timestamps = FALSE;
public function catering() {
return $this->belongsTo('Catering');
}
}
我可以做
$offers = Catering::find(1)->offers;
但,逆向不起作用:
$catering = Offer::find(1)->catering;
总是返回NULL。数据库具有正确的值。
is always returning NULL. Database has the right values.
优惠表有2列:
(id),int(cid)
primary(id), int(cid)
引用catering.id。
that references catering.id.
问题:
我如何访问这种关系的反面?
The question: How can i access the reverse side of this relation?
推荐答案
p>你说,我可以做
$offers = Catering::find(1)->offers;
和您的饮食
/ p>
and in your Catering
model you have
public function offers() {
return $this->hasMany('Offer', 'cid');
}
看起来你已经在这里定义了一个不同的外键( cid
)来使用它,而不是基本上应该使用的默认的 laravel
,所以要做相反的关系,你必须在中提供
模型的餐饮
功能
It seems like you've defined a different foreign key here (cid
) to use it instead of the default one that laravel
basically supposed to use, so, to do the reverse relation you have to do the same thing in your Offer
model's catering
function
public function catering() {
return $this->belongsTo('Catering', 'cid');
}
在 Laravel文档,它表示,你可以通过传递另一个参数来覆盖常规的外键$ $ c $ hasMany 方法,如
In the Laravel Documentation, it says that, you may override the conventional foreign key by passing a second argument to the hasMany
method, like
return $this->hasMany('Offer', 'custom_key');
同样的方式,定义与 Offer
model,您可以使用 belongsTo
方法,如
Same way, to define the inverse of the relationship on the Offer
model, you can use the belongsTo
method, like
return $this->belongsTo('Catering', 'custom_key'); // cid
这篇关于Laravel 4,如何访问反向一对多关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!