alfa/laravel-has-many-sync

Laravel 多对一同步

1.1.0 2018-08-13 09:35 UTC

This package is auto-updated.

Last update: 2024-09-11 16:38:24 UTC


README

允许为 Laravel 多对一关系提供同步方法。

安装

您可以通过 composer 安装此包

composer require alfa6661/laravel-has-many-sync

config/app.php 中注册 ServiceProvider

'providers' => [
    // ...
    Alfa6661\EloquentHasManySync\ServiceProvider::class,
],

使用方法

设置 HasMany 关系

class Customer extends Model
{
    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function contacts()
    {
        return $this->hasMany(CustomerContact::class);
    }
}

您可以通过以下方式访问同步方法

$customer->contacts()->sync([
    [
        'id' => 1,
        'name' => 'Alfa',
        'phone_number' => '123',
    ],
    [
        'id' => null,
        'name' => 'Adhitya',
        'phone_number' => '234,
    ]
]);

同步方法接受一个数组,该数组包含放置在中间表中的数据。任何不在给定数组中的数据都将从中间表中删除。因此,在完成此操作后,只有给定数组中的数据将存在于中间表中

不带删除的同步

如果您不想删除现有数据,可以在同步方法的第二个参数中传递 false 值。

$customer->contacts()->sync([
    [
        'id' => 1,
        'name' => 'Alfa',
        'phone_number' => '123',
    ],
    [
        'id' => null,
        'name' => 'Adhitya',
        'phone_number' => '234,
    ]
], false);

控制器中的示例用法。

class CustomersController extends Controller
{
    /**
     * Update the specified resource in storage.
     *
     * @param  CustomerRequest  $request
     * @param  Customer $customer
     * @return \Illuminate\Http\Response
     */
    public function update(CustomerRequest $request, Customer $customer)
    {
        DB::transaction(function () use ($customer, $request) {
            $customer->update($request->all());
            $customer->contacts()->sync($request->get('contacts', []));
        });

        return redirect()->route('customers.index');
    }
}