Laravel背包选择中继器字段中的2 1-n

mec1mxoz  于 2022-12-27  发布在  其他
关注(0)|答案(1)|浏览(111)

你好我有这个结构产品有很多颜色:
| 产品_表|可着色_表|颜色_表|
| - ------| - ------| - ------|
| 身份证|产品标识|身份证|
| 姓名|颜色标识|姓名|
| 颜色|||
我想存储产品的颜色数量,例如产品1有2个粉红色的项目,我尝试通过使用如下的repeater字段来实现这一点:

CRUD::field('colors')->label('Colors')->type('repeatable')->new_item_label('Add Info')->fields([
        [
            'name'       => 'color',
            'label'      => 'Color',
            'type'       => 'select',
            'model'      => 'App\Models\Color',
            'entity'     => 'color',
            'attribute'  => 'name',
            'wrapper'    => ['class' => 'form-group col-md-6 required'],
        ],
        [
            'name'    => 'number',
            'type'    => 'number',
            'label'   => 'Number',
            'wrapper' => ['class' => 'form-group col-md-6 required'],
        ],
    ]);

在我产品模型中:

public function color(): BelongsToMany
{
    return $this->belongsToMany(Color::class, 'colorables', 'product_id', 'color_id');
}

问题是它没有存储在colorables_table中(产品和颜色id),它只是存储来自repeater的JSON文件在products_table
你知道怎么解决吗?

ruarlubt

ruarlubt1#

    • 解决日期:**

为了解决这个问题,我为Product模型创建了一个 * observers
在这个 * observers * 的 * Created * 函数中,我放了下面的代码:

/**
 * Handle the Product "created" event.
 *
 * @param  \App\Models\Product  $product
 * @return void
 */
public function created(Product $product)
{ 
    foreach ($product->colors as $color) {
        $product->color()->attach($color['color_id']);
    }
}

就像一个符咒😀

相关问题