database icon indicating copy to clipboard operation
database copied to clipboard

💡 Subquery column alias injection

Open gam6itko opened this issue 3 years ago • 2 comments
trafficstars

I have an idea!

I have the query with subquery columns. I need to make aliases for subquery columns for having;

$result = $database
    ->select([
        'table1.id',
        $database->select('COUNT(1)')->from('table2')->where('inner_id', new Expression('table1.id')), // as cnt1
    ])
    ->from('table1')
    ->fetchAll();

now I need to do weird things like this

$result = $database
    ->select([
        'table1.id',
        new Fragment('('.$database->select('COUNT(1)')->from('table2')->where('inner_id', new Expression('table1.id')).') as cnt1'),
    ])
    ->from('table1')
    ->having('cnt1', 1)
    ->fetchAll();

We need something like ColumnAliasInjection to make it prettier

$result = $database
    ->select([
        'table1.id',
        new ColumnAliasInjection(
            $database->select('COUNT(1)')->from('table2')->where('inner_id', new Expression('table1.id')),
            'cnt1'
        )
    ])
    ->from('table1')
    ->having('cnt1', 1)
    ->fetchAll();

gam6itko avatar Aug 19 '22 13:08 gam6itko

Why not

->select([
        'id' => 'table1.id',
        'cnt1' => new Fragment('('.$database->select('COUNT(1)')->from('table2')->where('inner_id', new Expression('table1.id')).')'),
    ])

etc. ?

AnrDaemon avatar May 15 '24 22:05 AnrDaemon

has common traits with #200

gam6itko avatar Jun 11 '24 11:06 gam6itko