【问题标题】:Using sync with many to many relationship in laravel: PostgreSQL Pivot table doesn't update在 laravel 中使用多对多关系同步:PostgreSQL 数据透视表不更新
【发布时间】:2021-04-28 08:39:34
【问题描述】:

每当我尝试将输入数组同步到数据透视表时,我都会收到此错误:


Illuminate\Database\QueryException
SQLSTATE[23503]: Foreign key violation: 7 ERROR: insert or update on table "items_option_parcel" 
violates foreign key constraint "items_option_id_fk_2971521" DETAIL: Key (items_option_id)=(0) is not present in table "items_options". (SQL: insert into "items_option_parcel" ("items_option_id", "parcel_id") values (0, 168))


这是我的控制器的一行:

$parcel->parcel_options()->sync($request->input('parcel_options', []));

第一个模型中的功能:

public function parcelOptionsParcels()
    {
        return $this->belongsToMany(Parcel::class);
    }

第二个模型中的功能:

public function parcel_options()
    {
        return $this->belongsToMany(ItemsOption::class);
    }

【问题讨论】:

  • 您是否在该输入数组中传递了 0? parcel_options?
  • 不,它应该采用不为 0 的项目选项 id

标签: laravel postgresql eloquent


【解决方案1】:

我发现了问题,我检查了我的 pluck() 函数,我忘了用他们的 SKU 提取项目选项 ID,这就是为什么每次它说 0 id 不存在于表中,因为它没有得到完全被提取了。

我改变了这个:

$parcel_options = ItemsOption::all()>pluck('item_option_sku')>prepend(trans('global.pleaseSelect'), '');

到此

$parcel_options = 
ItemsOption::all()->pluck('item_option_sku','id')->prepend(trans('global.pleaseSelect'), '');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-05
    • 2021-05-31
    • 2016-03-29
    • 2014-12-07
    • 2018-09-23
    • 1970-01-01
    • 2021-02-13
    • 1970-01-01
    相关资源
    最近更新 更多