How can this be better optimized

Is there a way to do the following the following with a single db call rather than multiple as I currently have it setup

$projectLegs = ProjectsLegs::find()
->select(['ServTypeId'])
->where(['ProjId' => $model->ProjId])
->all();
foreach ($projectLegs as $projectLeg) {
	if(isset($projectLeg->ServTypeId)){
		$LegsServTypeIds[] = LstProjectsLegsServTypes::find()
							 ->select(['ServType'])
							 ->Where(['ServTypeId' => $projectLeg->ServTypeId])
							 ->scalar();
	}else{
		$LegsServTypeIds[] = '--';
	}
}

I’ve come up with the following

$items = ProjectsLegs::find()
->select(["IfNull(ServType, '--') Service"])
->leftJoin('lst_projects_legs_servtypes', 'projects_legs.ServTypeId = lst_projects_legs_servtypes.ServTypeId')
->where(['ProjId' => $model->ProjId])
->asArray()
->all();
foreach ($items as $item) {
	$LegsServTypeIds[] = $item['Service'];
}
if(isset($LegsServTypeIds)){
	return implode("\n", $LegsServTypeIds);
}else{
	return '';
}

Is this the right way to do things, or can this better be handles?

Looks great. If you use DB Query you might get rid of foreach also

1 Like

Use the relations between models. https://www.yiiframework.com/doc/guide/2.0/en/db-active-record#relational-data

I already had this in place originally, but sadly, when reviewing debugging logs on this problematic page I could see the app making SELECT * calls to retrieve individual columns. By switching to the above, I’ve already reduce load time by about half.