laravel eloquent 预加载时生成错误查询

laravel eloquent generates wrong query when eager-loading

我有这样的数据库 table:

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

我有外键 parent_product_template_id,它引用同一个 table 中的 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' 列

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

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

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