我的数据库表如下所示:
id, title, description (NULL), parent_product_template_id (NULL)
我有一个外键parent_product_template_id,它引用了同一个表中的id列。
在控制器中,我完成了查询:
$productTemplates = ProductTemplate::whereNull('parent_product_template_id')->get();
并压缩结果并将其传递给视图。
在视图中,我有这个前置循环:
@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’列
发布于 2018-05-30 07:29:01
如果在数据库中使用非标准外键,则需要在关系中显式声明它们。
在迁移中定义外键并不能修复雄辩的关系。
public function parent()
{
return $this->belongsTo('App\Models\ProductTemplate','parent_product_template_id','id');
}
https://stackoverflow.com/questions/50594220
复制相似问题