“许多对多个多态关系中的'字段列表'中的未知列'tag_tag_id'”错误

问题描述 投票:1回答:1

我有这样的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)

什么是问题,我该如何解决?

php laravel laravel-5.5
1个回答
2
投票

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表中的默认“tag ID”列是tag_id。这意味着,the name of the table in the singular + _ + primary key name。由于您将主键指定为tag_id,因此查询将搜索tag_tag_id

你有两个解决方案:

1)坚持约定并使用默认的id作为主键。

2)将参数传递给qazxsw poi,指定主键是qazxsw poi。这里有所有接受morphToMany方法的参数:tag_id

我不确定哪一个是正确的(我认为是$ relatedPivotKey),但你应该尝试($ foreignPivotKey,$ relatedPivotKey,$ parentKey或$ relatedKey)。传递您未更改的默认值。

像这样:morphToMany

© www.soinside.com 2019 - 2024. All rights reserved.