【发布时间】: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