如何使用同步方法传递 pivot table 附加列值

How to pass pivot table additional columns values using the sync method

我的数据透视表中有额外的列 table 命名为数字和权重,如下所示

  public function up()
     {
         $schema = static::SCHEMA;
         if (! empty($schema) && (Schema::getConnection()->getDriverName() == 'pgsql')) {
             $schema = $schema.'.';
         } else {
             $schema = '';
        }

    Schema::create($schema.'crime_species', function (Blueprint $table) use ($schema) {
        $table->bigInteger('crime_id')->unsigned();
        $table->bigInteger('species_id')->unsigned();
        $table->integer('number')->nullable();
        $table->integer('weight')->nullable();
        $table->timestamps();

        $table->foreign('crime_id')->references('id')->on($schema.'crimes');
        $table->foreign('species_id')->references('id')->on($schema.'species');
    });
}

我还有一个存储方法如下

   public function store(array $data = []): Crime
     {
         DB::beginTransaction();

         $item = $this->model::create($data);

    if ($item) {
        $item->fishingMethods()->sync($data['fishingMethods'] ?? []);
        $item->species()->sync($data['species'], ['number'=>4, 'weight'=>20]?? []);
        $item->offences()->sync($data['offences'] ?? []);
        $item->confiscatedItems()->sync($data['confiscatedItems'] ?? []);

        DB::commit();

        return $item;
    }

    DB::rollBack();

    throw new GeneralException(__('There was a problem creating this user. Please try again.'));
}

我遇到的困难部分是传递额外的列值 $item->species()->sync($data['species'], ['number'=>4, 'weight'=>20]?? []);数字的额外列值 4 和重量的 20 未插入数据透视表 table.

你能帮帮我吗?

sync 方法接受一组 ID 以放置在中间 table 上。任何不在给定数组中的 ID 将从中间 table 中删除。所以,这个操作完成后,中间只会存在给定数组中的ID table:

$item->species()->sync([1, 2, 3]);

您还可以通过以下 ID 传递额外的中间 table 值:

$item->species()->sync([1 => ['number' => 4, 'weight' => 20]);

请注意,您必须使用嵌套数组。数组的键是要关联的元素的 ID,其内容是数据透视表的额外列 table.

$attach = collect($data['species'])->mapWithKeys(function ($specie) {
    return [$specie => ['number' => 4, 'weight' => 20]];
});

$item->species()->sync($attach);