f-liva/laravel-hasmany-sync

轻松同步 Laravel 的 HasMany 关联

v1.2.0 2024-06-04 12:39 UTC

This package is auto-updated.

Last update: 2024-09-04 13:07:27 UTC


README

Latest Version on Packagist License Codecov TravisCI StyleCI

使用此包,您将能够像通常为 BelongsToMany 关联一样同步您的 HasMany 关联。使用方法相同,请遵循官方 Laravel 文档。

感谢 korridor/laravel-has-many-sync 提供的原始想法。此包使用原始 Laravel 方法操作重建了机制。

安装

您可以使用以下命令通过 composer 安装此包:

composer require f-liva/laravel-hasmany-sync

用法

按照您通常的方式配置您的 HasMany 关联

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

像在 BelongsToMany 关联中一样同步关系

$customer->contacts()->sync([1, 2, 3]);

// Or with attributes...

$customer->contacts()->sync([1 => ['name' => 'Foo'], 2 => ['name' => 'Bar'], 3]);

sync 方法接受与 Eloquent Relationships - Syncing Relations 中描述的相同参数

您也可以在不了解相关记录标识符的情况下同步关系。在这种情况下,在调用中指定 syncRelatedKey: false 参数。

$customer->contacts()->sync([1, 2, 3], syncRelatedKey: false);

// Or with attributes...

$customer->contacts()->sync([['name' => 'Foo'], ['name' => 'Bar'], ...]);

贡献

我欢迎建议和贡献。只需创建一个 issue 或一个 pull request。

测试

运行所有测试的 composer test 命令使用 phpunit。运行所有测试并创建 coverage 文件夹中的覆盖率报告的 composer test-coverage 命令。

代码格式化/检查

使用 composer fix 命令使用 php-cs-fixer 格式化代码。使用 composer lint 命令使用 phpcs 检查代码。

许可证

此包根据 MIT 许可证 (MIT) 许可。有关更多信息,请参阅许可证文件