【问题标题】:SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'field list'SQLSTATE [42S22]:未找到列:1054 '字段列表'中的未知列 'id'
【发布时间】:2020-08-10 05:06:50
【问题描述】:

我有 product_variants 表,它与其他 2 个表数据 productsvariants 相关联

当我尝试更新我的产品时,它会返回此错误

SQLSTATE[42S22]:未找到列:1054 '字段中的未知列 'id' list' (SQL: 更新product_variants 设置id = 0118d682-970f-4859-b30b-e1c79df9c342, parent_id = ?, name = 接口,slug = 接口,photo = ?,type = 文本区域, active = 是,created_at = 2020-08-05 14:57:42,updated_at = 2020-08-05 14:57:42,pivot = {"product_id":"4ea5f41f-aa2f-46d4-b033-e4e875cc8ff4","variant_id":"0118d682-970f-4859-b30b-e1c79df9c342"}, children = [{"id":"7efe338d-9026-4fe8-b16f-6b99bc51871a","parent_id":"0118d682-970f-4859-b30b-e1c79df9c342","name":"1x RJ45, 1x SD (XC/HC) 读卡器, 1x (4K @ 60Hz) HDMI, 1x Mini-DisplayPort, 2x Type-A USB3.2 Gen1, 1x Type-A USB3.2 Gen2, 1x Type-C (USB3.2 Gen2 / DP), 1x Type-C USB3.2 Gen2x2","slug":"1x RJ45, 1x SD (XC/HC) 读卡器、1x (4K @ 60Hz) HDMI、1x Mini-DisplayPort、 2x Type-A USB3.2 Gen1、1x Type-A USB3.2 Gen2、1x Type-C(USB3.2 Gen2 /DP), 1x Type-C USB3.2 Gen2x2","photo":null,"type":"textarea","active":"yes","created_at":"2020-08-05 14:57:42","updated_at":"2020-08-05 14:57:42"}] 其中product_id = 4ea5f41f-aa2f-46d4-b033-e4e875cc8ff4 和variant_id (0))

代码

product_variants迁移

public function up()
{
    Schema::create('product_variants', function (Blueprint $table) {
        $table->primary(['product_id', 'variant_id']);
        $table->uuid('product_id')->nullable();
        $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
        $table->uuid('variant_id')->nullable();
        $table->foreign('variant_id')->references('id')->on('variants');
    });
}

product model

public function variations(){
    return $this->belongsToMany(Variant::class, 'product_variants', 'product_id', 'variant_id');
}

variant model

public function products(){
    return $this->belongsToMany(Product::class, 'product_variants', 'variant_id', 'product_id');
}

知道导致问题的原因吗?

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    我建议自己制作Pivot Model并坦率地设置主键:

    use Illuminate\Database\Eloquent\Relations\Pivot;
    
    class ProductVariants extends Pivot
    {
       protected $primaryKey = ['product_id', 'variant_id'];
    public $incrementing = false;
    }
    

    在此之后你应该修改你的关系:

    public function variations()
        {
            return $this->belongsToMany(Variant::class)
                            ->using(ProductVariants::class);
        }
    

    【讨论】:

    • 谢谢,但问题是我没有 ProductVariants 模型,因为这是关系表(只需获取两个 id)它不需要模型(此表使用 sync存储数据的方法)
    猜你喜欢
    • 1970-01-01
    • 2016-07-12
    • 2019-10-14
    • 2021-10-31
    • 2018-10-23
    • 2017-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多