ORM: with recursive

This commit is contained in:
Yurii
2026-02-03 13:25:18 +02:00
parent 9d7d9ac29c
commit bd9bacb210
5 changed files with 167 additions and 14 deletions
@@ -29,10 +29,12 @@
namespace tests\unit\Espo\ORM;
use Espo\ORM\Query\Part\Condition as Cond;
use Espo\ORM\Query\Part\Join;
use Espo\ORM\Query\Part\Where\Comparison;
use Espo\ORM\Query\Part\WhereClause;
use Espo\ORM\Query\SelectBuilder;
use Espo\ORM\Query\UnionBuilder;
use Espo\ORM\QueryComposer\Part\FunctionConverterFactory;
use Espo\ORM\QueryComposer\Part\FunctionConverter;
@@ -3629,4 +3631,73 @@ class MysqlQueryComposerTest extends TestCase
$this->assertEquals($expectedSql, $sql);
}
public function testWithRecursive1(): void
{
$query = (new SelectBuilder())
->select('id')
->from('Test', 'test')
->withRecursive(
UnionBuilder::create()
->all()
->query(
SelectBuilder::create()
->select([
'order',
'id',
'parentId'
])
->from('Category')
->where(['parentId' => null])
->build()
)
->query(
SelectBuilder::create()
->select([
'order',
'id',
'parentId',
])
->from('Category')
->join(
Join::createWithTableTarget('CommonTable', 'comTab')
->withConditions(
Cond::equal(
Expression::column('comTab.id'),
Expression::column('parentId'),
)
)
)
->where(['parentId' => null])
->build()
)
->build(),
'CommonTable'
)
->join(
Join::createWithTableTarget('CommonTable', 'comTab')
->withConditions(
Cond::equal(
Expression::column('comTab.id'),
Expression::column('categoryId'),
)
)
)
->withDeleted()
->build();
$sql = $this->query->composeSelect($query);
$expected =
"WITH RECURSIVE `common_table` AS (" .
"(SELECT category.order AS `order`, category.id AS `id`, category.parent_id AS `parentId` FROM `category` " .
"WHERE category.parent_id IS NULL) UNION ALL " .
"(SELECT category.order AS `order`, category.id AS `id`, category.parent_id AS `parentId` FROM `category` " .
"JOIN `common_table` AS `comTab` ON comTab.id = category.parent_id " .
"WHERE category.parent_id IS NULL)) SELECT test.id AS `id` FROM `test` AS `test` " .
"JOIN `common_table` AS `comTab` ON comTab.id = test.category_id";
$this->assertEquals($expected, $sql);
}
}
+4
View File
@@ -66,6 +66,10 @@ class Article extends TestEntity
}
class Category extends TestEntity
{
}
class Job extends TestEntity
{
public function getFromContainerOriginal(string $attribute)
+11
View File
@@ -601,4 +601,15 @@ return [
],
],
],
'Category' => [
'attributes' => [
'id' => [
'type' => Entity::ID,
],
'parentId' => [
'type' => Entity::FOREIGN_ID,
],
],
],
];