QueryBuilder v200.4.1
Fluent-аргументы для DataLoaderService (SELECT / INSERT / UPDATE / DELETE) на AbstractWith + #[With]/#[WithItem].
Зачем: собрать table / columns / conditions / values / order / limit / offset без сырого массива.
Namespace: DevCraft\Builders
Путь: devcraft/src/classes/Builders/QueryBuilder.php
См. также: DataLoader, DataLoaderService, SortDirection, With attributes
Свойства (#[With] / #[WithItem])
| Свойство | Атрибуты | Методы |
|---|---|---|
$table | #[With] | withTable |
$columns | #[With, WithItem('string')] | withColumns, withColumnsItem |
$conditions | #[With, WithItem('string', 'mixed')] | withConditions, withConditionsItem |
$values | #[With, WithItem('string', 'mixed')] | withValues, withValuesItem |
$primaryKey | #[With] (по умолчанию id) | withPrimaryKey |
$order | #[With, WithItem('string', [SortDirection::class, 'string'])] | withOrder, withOrderItem |
$limit / $offset | #[With] | withLimit, withOffset |
Условия (conditions)
Простое равенство: withConditionsItem('user_id', 1) → колонка = значение.
Оператор — массив с ключами op и value. Разбор делает DataLoaderService при SELECT / UPDATE / DELETE.
op | value | Что получается |
|---|---|---|
in | список или одно значение | IN (…); значение уходит в Parameter Cycle |
like | строка с % / _ | LIKE |
find_in_set | id / строка | FIND_IN_SET(?, \колонка`)черезExpression`; значение не вклеивается в SQL |
| любой другой | как у Cycle where | where($column, $op, $value) |
Группа «или» — ключ _or: список наборов условий. Внутри набора — через и; наборы между собой — через или. С остальными условиями снаружи группа тоже через и.
->withConditionsItem('approve', 1) // всегда
->withConditionsItem('_or', [
['id' => ['op' => 'in', 'value' => $newsIds]],
['tags' => ['op' => 'like', 'value' => '%' . $tag . '%']],
['category' => ['op' => 'find_in_set', 'value' => $catId]],
]);
// SQL-смысл: approve = 1 AND ( id IN (…) OR tags LIKE … OR FIND_IN_SET(…) )Тот же формат можно передать целиком через withConditions([...]).
Ручные методы
| Метод | Зачем |
|---|---|
create(string $table) | Старт цепочки |
build() | Массив для loadData (order → `'ASC' |
load() | Все строки через DataLoaderService::loadData |
first() | Первая строка или [] |
insert() | INSERT по values → созданная строка ([] при ошибке) |
update() | UPDATE по conditions → все совпавшие строки |
delete() | DELETE по conditions → bool (без conditions — false) |
Пример SELECT
use DevCraft\Builders\QueryBuilder;
use DevCraft\Core\Enums\SortDirection;
$user = QueryBuilder::create('users')
->withColumnsItem('user_id')
->withColumnsItem('name')
->withConditionsItem('user_id', $userId)
->withOrderItem('name', SortDirection::Asc)
->withLimit(1)
->first();Пример INSERT / UPDATE / DELETE
use Cycle\Database\Injection\Fragment;
use DevCraft\Builders\QueryBuilder;
$row = QueryBuilder::create('pm')
->withValues([
'subj' => 'Тема',
'text' => 'Текст',
'user' => $userId,
'folder' => 'inbox',
])
->insert();
QueryBuilder::create('users')
->withValues([
'pm_all' => new Fragment('pm_all+1'),
'pm_unread' => new Fragment('pm_unread+1'),
])
->withConditionsItem('user_id', $userId)
->update();
$ok = QueryBuilder::create('tags')
->withConditionsItem('news_id', $newsId)
->withConditionsItem('tag', $tag)
->delete();Пример: OR из in / like / find_in_set
Тот же приём, что у ленты подписок Notifications (SubscriptionFeedService): один QueryBuilder, снаружи равенство, внутри _or — разные типы совпадения.
use DevCraft\Builders\QueryBuilder;
use DevCraft\Core\Enums\SortDirection;
$orGroup = [
['id' => ['op' => 'in', 'value' => $newsIds]],
['tags' => ['op' => 'like', 'value' => '%' . $tagId . '%']],
['category' => ['op' => 'find_in_set', 'value' => $catId]],
['autor' => ['op' => 'in', 'value' => $authorNames]],
];
$rows = QueryBuilder::create('post')
->withColumns(['id', 'title', 'alt_name', 'category', 'date'])
->withConditionsItem('approve', 1)
->withConditionsItem('_or', $orGroup)
->withOrderItem('date', SortDirection::Desc)
->withLimit(10)
->load();