napp / dbalcore
项目的 DBAL 核心
2.0.0
2020-10-29 21:44 UTC
Requires
- php: ^7.1|^8.0
- illuminate/database: ^5.8|^6.0|^7.0|^8.0
- illuminate/support: ^5.8|^6.0|^7.0|^8.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.16
- orchestra/testbench: ^5.0|^6.3
- phpunit/phpcov: ^6.0|^7.0|^8.0
- squizlabs/php_codesniffer: ^3.1
This package is auto-updated.
Last update: 2024-08-29 04:37:17 UTC
README
此包扩展了 Laravel 查询构建器,具有一个很好的 基础仓库
,并提供了一系列有用的 标准
以构建查询。
仓库
基础仓库具有各种有用的方法。
事务
return $this->transaction(function () use ($data) { User::update($data); });
标准
标准
是在自定义类中构建自定义查询逻辑并在项目中重用的一种方式。与基础仓库一起使用,
$this->criteriaCollection = new CriteriaCollection(); $this->criteriaCollection ->reset() ->add(new WithRelationCriterion('contentGroups')) ->add(new WithRelatedUserCriterion($request->user())) ->add(new WithSearchQueryCriterion('foobar', 'name')); $forms = $this->formsRepository->getAllMatchingCriteria($this->criteriaCollection);
QueryBuilder 使用
此包通过以下方法扩展 Laravel 查询构建器
替换
使您能够在 Laravel 中使用 REPLACE INTO
MySQL 语法。只需这样做
User::replace($data);
insertOnDuplicateKey
从模型调用 insertOnDuplicateKey
或 insertIgnore
,并传递要插入其表中的数据的数组。
$data = [ ['id' => 1, 'name' => 'name1', 'email' => 'user1@email.com'], ['id' => 2, 'name' => 'name2', 'email' => 'user2@email.com'], ]; User::insertOnDuplicateKey($data); User::insertIgnore($data);
自定义 ON DUPLICATE KEY UPDATE 子句
仅更新某些列
如果您只想更新某些列,请将它们作为第二个参数传递。
User::insertOnDuplicateKey([ 'id' => 1, 'name' => 'new name', 'email' => 'foo@gmail.com', ], ['name']); // The name will be updated but not the email.
使用自定义值更新
您可以通过传递关联数组来自定义当行已存在时将更新的列的值。
在以下示例中,如果 id = 1 的用户不存在,它将创建一个名为 'created user' 的用户。如果它已存在,则将更新为 'updated user'。
User::insertOnDuplicateKey([ 'id' => 1, 'name' => 'created user', ], ['name' => 'updated user']);
生成的 SQL 是
INSERT INTO `users` (`id`, `name`) VALUES (1, "created user") ON DUPLICATE KEY UPDATE `name` = "updated user"
您可以将键/值对和列名组合在第二个参数中,以指定使用自定义文字或表达式或默认 VALUES(column)
更新的列。例如
User::insertOnDuplicateKey([ 'id' => 1, 'name' => 'created user', 'email' => 'new@gmail.com', 'password' => 'secret', ], ['name' => 'updated user', 'email]);
将生成
INSERT INTO `users` (`id`, `name`, `email`, `password`) VALUES (1, "created user", "new@gmail.com", "secret") ON DUPLICATE KEY UPDATE `name` = "updated user", `email` = VALUES(`email`)
交叉表
从 BelongsToMany
关系调用 attachOnDuplicateKey
和 attachIgnore
以在其交叉表中运行插入。您可以传递 attach
所接受的所有格式的数据。
$pivotData = [ 1 => ['expires_at' => Carbon::today()], 2 => ['expires_at' => Carbon::tomorrow()], ]; $user->roles()->attachOnDuplicateKey($pivotData); $user->roles()->attachIgnore($pivotData);