Laravel 4, how to access reverse one-to-many relation?

不羁岁月 提交于 2019-12-06 10:39:05

You said that, I am able to do

$offers = Catering::find(1)->offers;

and in your Catering model you have

public function offers() {
    return $this->hasMany('Offer', 'cid');
}

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');
}

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');

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!