$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.