Laravel 4,如何访问反向一对多关系? [英] Laravel 4, how to access reverse one-to-many relation?

查看:607
本文介绍了Laravel 4,如何访问反向一对多关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

<?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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆