Lazy Load Relation And Select

I have a model with a relation that’s set to lazy load.

I wanted to try and set the select so I could use a function within SQL.




$models = Model::find()

    ->joinWith(['item' => function($q) {

        $q->select(['SQL_FUNC(id) AS result']);

    }], false)

    ->all();


$models[0]->item; //This will use SELECT * FROM ...



But when I try to access the related model it ignores the select and uses the all columns * instead.

Not sure if this is expected behaviour and if I’m doing it wrong?

Lazy loading is a totally different query, so yes, I suppose this is expected.

Why not use eager loading instead?..

PS. Seems like you’re trying to do some tricky stuff like selecting aggregate.

Plz post your actual problem, maybe there’s a simpler solution.

This is my query.




$banners = Banners::find()

    ->joinWith(['item0' => function($q) {

        $q->select(['uri', 'FUNC(image) AS image'])

            ->joinWith(['itemDates' => function($q) {

                $q->onCondition('NOW() BETWEEN start AND end AND site_item_dates.status = 1');

            }]);

    }])

    ->where('site_items.status = 1 AND site_item_dates.item IS NOT NULL')

    ->all();



It works as expected and returns an array of models.

I was just trying to optimize the query because when I access the “item0” relation it joins the “itemDates” relation again when it’s not needed.

With eager loading when accessing the relation,


$banners[0]->item0


SELECT `uri`, FUNC(image) AS image FROM `site_items`

LEFT JOIN `site_item_dates` ON (`site_items`.`id` = `site_item_dates`.`item`) AND (NOW() BETWEEN start AND end AND site_item_dates.status = 1)

WHERE `id`=23

With lazy loading?


$banners[0]->item0


SELECT * FROM `site_items` WHERE `id`=23

Lazy load removes the unneeded join but loses the specified SELECT.

Try to comment out $q->select() first, or add PKs and FKs to select array.