【问题标题】:Eloquent Relation Fail When Foreign Keys Same当外键相同时,雄辩的关系失败
【发布时间】:2014-06-29 11:37:55
【问题描述】:

当两个表在索引上具有相同的列名时,我无法连接表,直到我将主表字段更改为“id”。我不能使用查询生成器;必须在雄辩的 orm 上找到解决方案。

主表,

product_id, ...

子表,

sub_product_id, product_id, ...

这些是模型,

require_once(APPPATH . 'models/connection.php');

use Illuminate\Database\Eloquent\Model as Eloquent;

class Credit extends Eloquent {

    public $timestamps = false;

    public $table = 'tbl_credit';


    public function periods() {

        return $this->hasMany('Period', '**product_id**');
    }
}

和子模型,

require_once(APPPATH . 'models/connection.php');

use Illuminate\Database\Eloquent\Model as Eloquent;


class Period extends Eloquent {

    public $timestamps = false;

    public $table = 'tbl_credit_period';


    public function credit() {
        return $this->belongsTo('Credit', '**product_id**');
    }
}

代码是这样的

Credit::with('periods')->get()->toArray()

给出结果

array(product_id => .., periods => null)

如果我将信用表主键从product_id 更改为id,那么它可以工作。

【问题讨论】:

  • 显示代码和错误,因为现在它会猜测你的意思。
  • 代码已添加,谢谢

标签: eloquent


【解决方案1】:

问题在于第一个表键和第二个表外键的命名不同,而是您不遵守 Eloquent 模型的命名约定。

如果您没有明确指定 id,Eloquent 将检查它作为主键,所以这应该适合您(尽管我建议不要将这些列命名为相同):

// Credit model
protected $primaryKey = 'product_id';

为了清楚起见 - 您的代码不是连接表,而是使用 where in 子句运行另一个查询,Laravel 应该正确获取相关行。问题在于稍后将获取的结果与他们的 Credit 父母匹配,这就是您在那里得到null 的原因。

【讨论】:

  • 你真是个天才!!多么伟大的框架,缺乏文档。
  • 很高兴我提供了帮助,并且对于文档.. 我认为它们非常好,而且这件事在开始时就在红框中;)laravel.com/docs/eloquent#basic-usage
猜你喜欢
  • 1970-01-01
  • 2017-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多