【问题标题】:laravel eloquent generates wrong query when eager-loadinglaravel eloquent 在急切加载时生成错误的查询
【发布时间】:2018-05-29 23:08:30
【问题描述】:

我有这样的数据库表:

id, title, description (NULL), parent_product_template_id (NULL)

我有外键 parent_product_template_id 引用同一个表中的 id 列。

在控制器中我完成了查询:

$productTemplates = ProductTemplate::whereNull('parent_product_template_id')->get();

并压缩结果并将它们传递给视图。

在视图中我有这个 forelse 循环:

@foreach($productTemplates as $productTemplate)
   $productTemplate->childs
@endforeach

ProductTemplate 模型如下所示。

class ProductTemplate extends Model
{
  public $timestamps = false;
  public function parent()
  {
    return $this->belongsTo('App\Models\ProductTemplate');
  }
  public function childs()
  {
    return $this->hasMany('App\Models\ProductTemplate');
  }
}

最后的问题是,在运行代码时,我收到了这个错误消息

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'product_templates.product_template_id' in 'where clause' (SQL: select * from `product_templates` where `product_templates`.`product_template_id` = 1 and `product_templates`.`product_template_id` is not null) (View: E:\wamp\www\SyriaShop\resources\views\admin\product-template\index.blade.php)

为什么以及如何使用如此奇怪的键 'product_template_id' 而不是真正的 'id' 列

【问题讨论】:

  • 你的数据库表的名字是什么?
  • 表名:product_templates
  • 您已经自行设置了密钥parent_product_template_id,但这应该可以工作public function parent() { return $this->belongsTo('App\Models\ProductTemplate','parent_product_template_id'); }

标签: laravel eloquent eager-loading laravel-5.6


【解决方案1】:

如果您在数据库中使用非标准外键,那么您需要在关系中明确声明它们。

在迁移中定义外键并不能修复 eloquent 关系。

public function parent()
{
    return $this->belongsTo('App\Models\ProductTemplate','parent_product_template_id','id');
}

【讨论】:

  • 我修复了 parent 和 childs 方法的声明。它工作得非常好。谢谢。
猜你喜欢
  • 2016-08-17
  • 1970-01-01
  • 2021-10-02
  • 2017-10-09
  • 1970-01-01
  • 2018-03-29
  • 2013-06-10
  • 2019-07-08
  • 1970-01-01
相关资源
最近更新 更多