Code:
<?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;
but,逆函数不起作用:
$catering = Offer::find(1)->catering;
总是返回 NULL。数据库具有正确的值。
报价表有 2 列:
主要(id),int(cid)
引用 catering.id。
问题:我如何访问这种关系的反面?
你之前这么说,I am able to do
$offers = Catering::find(1)->offers;
并在你的Catering
你有的型号
public function offers() {
return $this->hasMany('Offer', 'cid');
}
看来您在这里定义了不同的外键(cid
) 使用它来代替默认的laravel
基本上应该使用,所以,要做相反的关系,你必须在你的Offer
楷模catering
功能
public function catering() {
return $this->belongsTo('Catering', 'cid');
}
In the Laravel 文档 http://laravel.com/docs/eloquent#one-to-many,它表示,您可以通过将第二个参数传递给hasMany
方法,比如
return $this->hasMany('Offer', 'custom_key');
同样的方式,定义关系的逆Offer
模型,您可以使用belongsTo
方法,比如
return $this->belongsTo('Catering', 'custom_key'); // cid
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)