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()
->where(['ProjId' => $model->ProjId])
foreach ($projectLegs as $projectLeg) {
		$LegsServTypeIds[] = LstProjectsLegsServTypes::find()
							 ->Where(['ServTypeId' => $projectLeg->ServTypeId])
		$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])
foreach ($items as $item) {
	$LegsServTypeIds[] = $item['Service'];
	return implode("\n", $LegsServTypeIds);
	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.

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.