relationLoaded shouldn't actually hit the DB. Are you sure about that one, that the DB Query comes from this part?
Feb 24, 2021
4
Level 3
Retrieving a loaded relationship but do not hit database if missing
I have the relationship:
public function collectionAddress(): BelongsTo
{
return $this->belongsTo(OrderAddress::class, 'collection_address_id');
}
In some parts of my app, the relationship does not exist but I want to load in an object to use within the request. So I can do:
$model->collectionAddress = new OrderAddress($data);
This all works fine until the relationship or key does not exist within a particular table. i.e. a ReturnDelivery model is another model that can be used in this logic and it does not have a collection_address_id column in the table.
The second option below does work while the top two do not. I assume the relation loaded call is for an eagerly loaded collection as opposed to a single belongsTo
Is there a better way to check if the belongs to relationship is loaded, without querying the DB?
// Fails as we try to hit the DB
if ($this->shippable->collectionAddress) {
return OrderAddressData::fromOrderAddress($this->shippable->collectionAddress);
}
// Fails as we try to hit the DB
if ($this->shippable->relationLoaded('collectionAddress')) {
return OrderAddressData::fromOrderAddress($this->shippable->collectionAddress);
}
// doesn't work, tries to hit DB
if ($collectionAddress = $this->shippable['collectionAddress'] ?? null) {
return OrderAddressData::fromOrderAddress($collectionAddress);
}
// Works
if ($collectionAddress = $this->shippable->toArray()['collectionAddress'] ?? null) {
return OrderAddressData::fromOrderAddress($collectionAddress);
}
Please or to participate in this conversation.