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

心不动则不痛 提交于 2019-12-22 18:31:42

问题


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

I am able to do

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

but, the inverse is not working:

$catering = Offer::find(1)->catering;

is always returning NULL. Database has the right values.

Offer table has 2 columns:

primary(id), int(cid)

that references catering.id.

The question: How can i access the reverse side of this relation?


回答1:


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


来源:https://stackoverflow.com/questions/18913560/laravel-4-how-to-access-reverse-one-to-many-relation

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