n3pix's avatar
Level 1

How do I conditionally load nested relationship?

$warehouseToBeLoaded->slots->load([
    'storable',
    'storable.rewards'
]);

I have the above code to load relationships of a model instance. As you can see I'm also loading a nested relationshio storable.rewards but storable is a polymorphic relationship and some types of storable don't have rewards relationship and this causes my query to fail with the below error:

Call to undefined relationship [rewards] on model [App\\Models\\Crop]

How can I conditionally load storable.rewards relationship? What would be the most SQL-wise efficient?

1 like
4 replies
vincent15000's avatar

Can you show your storable model please ?

Why do you say conditionaly ? I don't see any condition to load the relationship.

1 like
Feelyoung's avatar
$warehouseToBeLoaded->slots->load([
	'storable' => function ($query) {
		$query->constrain([
			RewardsModel::class => function ($query) {
				// ...
			},
			OtherModel::class => function ($query) {
				// ...
			},
		]);
	}
]);
1 like

Please or to participate in this conversation.