orm icon indicating copy to clipboard operation
orm copied to clipboard

Add support for inner Selects in SQL generation for joined entities

Open mrakolice opened this issue 5 years ago • 6 comments

Example of generated SQL:

SELECT table1_alias.* FROM
(
    SELECT id, field1,  field2 from table1
    WHERE field1=%val1
    LIMIT 10 OFFSET 20
) as table1_alias
LEFT JOIN (
SELECT field3, field4, table1_id FROM table2
WHERE field3=%val2
LIMIT 10 OFFSET 20
) as table2_alias ON table1_alias.id = table2_alias.table1_id

mrakolice avatar Jan 20 '20 02:01 mrakolice

This is already possible for FROM part (though API is not publicly announced) , for the JOIN part see #23

wolfy-j avatar Jan 20 '20 09:01 wolfy-j

Is this possible when you are working with loaders, or I should use only select()->buildQuery() notation?

mrakolice avatar Jan 20 '20 23:01 mrakolice

Can you post some usages of this API or where I can find it in source code?

mrakolice avatar Jan 21 '20 07:01 mrakolice

$select = TestModel::orm()->select()->limit(10)->offset(4);

TestModel::orm()->select()->from((new Fragment('(' . $select->sqlStatement() . ') as testModel'));

I'm finally find this solution.

mrakolice avatar Jan 21 '20 07:01 mrakolice

Yes, this will work :) Later update is require for JOINs.

wolfy-j avatar Jan 21 '20 07:01 wolfy-j

TestModel::orm() ~ (new Orm())->getRepository(TestModel::class)

$sqlStatement = TestModel::orm()->select()->limit(10)->offset(0)->sqlStatement();
 
$resultStatement = preg_replace('/\sAS\s\"c\d+\"/', '', $sqlStatement);
$from = TestModel::orm()->select()->from(
        (new Fragment('(' . $resultStatement . ') as "' .
            TestModel::orm()->select()->getBuilder()->getLoader()->getAlias() . '"'))
);

I'll leaving this for future generations.

mrakolice avatar Jan 21 '20 08:01 mrakolice