我有一个像这样的Tag
模型:
class Tag extends Model
{
protected $primaryKey = 'tag_id';
protected $fillable = ['name'];
public function products()
{
return $this->morphedByMany(Product::class, 'taggable');
}
}
另一方面,有一个像这样的产品模型:
class Product extends Model
{
protected $primaryKey = 'product_id';
protected $fillable = ['code', 'title', 'description'];
public function tags()
{
return $this->morphToMany(\Modules\Tag\Entities\Tag::class, 'taggable');
}
}
正如您所看到的,它们之间存在很多多态关系。但每次我想存储带有这样一些标签的产品时:
public function store(ProductFormRequest $request)
{
$newProduct = Product::create($request->all());
if ($request->has('tags')) {
$newProduct->tags()->sync($request->get('tags'));
}
return $this->item($newProduct, new ProductTransformer);
}
我收到此错误:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tag_tag_id' in 'field list' (SQL: select `tag_tag_id` from `taggables` where `taggable_id` = 4 and `taggable_type` = Modules\\Product\\Entities\\Product)
问题是什么以及如何解决?
最佳答案
Many To Many Polymorphic Relations :
products
id - integer
name - string
tags
id - integer
name - string
taggables
tag_id - integer
taggable_id - integer
taggable_type - string
如您所见,taggables
表中的默认“标签 ID”列是 tag_id
。这意味着,单数表名称
+ _
+ 主键名称
。由于您将主键指定为 tag_id
,因此查询将搜索 tag_tag_id
。
您有两种解决方案:
1) 遵守约定并使用默认的 id
作为主键。
2) 将参数传递给morphToMany
,指定primaryKey 为tag_id
。这里有接受 morphToMany
方法的所有参数:MorphToMany API 。
我不确定哪一个是正确的(我认为是 $latedPivotKey),但您应该尝试($foreignPivotKey、$latedPivotKey、$parentKey 或 $latedKey)。传递您不更改的默认值。
类似这样的:$this->morphToMany(\Modules\Tag\Entities\Tag::class, 'taggable', null, null, 'tag_id');
关于php - "Unknown column ' tag_tag_id ' in ' 字段列表 '"多对多多态关系上的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47842835/