【问题标题】:Laravel 4, how to access reverse one-to-many relation?Laravel 4,如何访问反向一对多关系?
【发布时间】:2013-09-20 09:43:10
【问题描述】:

代码:

<?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。数据库具有正确的值。

报价表有 2 列:

primary(id), int(cid)

引用了 catering.id。

问题: 我如何访问这种关系的反面?

【问题讨论】:

  • 没有看到正在生成的 SQL,我不能肯定地说。但是您是否尝试过使用$this-&gt;belongsTo('Catering', 'cid');,因为我认为您的用途是在offer 表中查找列catering_id。
  • @carbontwelve 我认为你是对的

标签: php laravel laravel-4 eloquent


【解决方案1】:

你这么说,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');
}

在Laravel Documentation 中,它说,您可以通过将第二个参数传递给hasMany 方法来覆盖常规外键,例如

return $this->hasMany('Offer', 'custom_key');

同样,要在Offer模型上定义逆关系,可以使用belongsTo方法,比如

return $this->belongsTo('Catering', 'custom_key'); // cid

【讨论】:

    猜你喜欢
    • 2016-08-18
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 2017-08-07
    • 1970-01-01
    • 1970-01-01
    • 2013-09-19
    • 2021-11-19
    相关资源
    最近更新 更多