laravel-macros/eloquent-insert-as-model

此包已被弃用且不再维护。未建议替代包。

将 `insertAsModel` 宏添加到 Eloquent Builder。与 `insert` 不同,`insertAsModel` 方法将确保所有插入的值都会经过模型的类型转换和修改器。

1.0.0 2021-04-25 12:38 UTC

This package is auto-updated.

Last update: 2022-05-20 10:31:15 UTC


README

此包将向 Laravel 的 Eloquent Builder 类添加 insertAsModel 宏。

insert 不同,insertAsModel 方法将确保所有插入的值都会经过模型的类型转换和修改器,然后再将其传递给 insert 方法。

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

安装

您可以通过 composer 安装此包

composer require laravel-macros/eloquent-insert-as-model

用法

假设您有

class User extends Model
{
     protected $casts = [
        'options' => 'json',
        'shelf'   => 'collection',
    ];
}

通常,如果您使用 Model::insert 方法插入一批条目,类型转换和修改器将被忽略,您需要自己将值转换为字符串。

使用此包,您可以使用与 Model::create 相同的方式插入值,其中所有适当的类型转换和修改逻辑都将得到应用。

User::insertAsModel([
    [
        'options' => ['sms' => true],
        'shelf'   => collect(['book1', 'book2', 'book3']),
    ],
    [
        'options' => ['sms' => false],
        'shelf'   => collect(['book1', 'book2']),
    ],
]);

这将防止您进行类似 'options' => json_encode(['sms' => true]) 的黑客操作。

注意:insertAsModel 不是一个多次 create 调用。它将直接插入到数据库中(就像 insert 一样)。例如,它不会触发模型的事件。

测试

composer test

# Test Coverage with XDebug enabled
composer test-coverage

变更日志

请参阅 CHANGELOG 了解最近更改的更多信息。

贡献

请参阅 CONTRIBUTING 了解详细信息。

安全漏洞

请查阅 我们的安全策略 了解如何报告安全漏洞。

鸣谢

许可协议

MIT 许可协议 (MIT)。请参阅 许可文件 了解更多信息。