I wonder if is there any method in Laravel that check if column_id
is not null and contains a valid id, then bring the relation if It is ?
so for example:
instead of doing this:
if ($order->billing_address_id && $billingAddress = $order->billingAddresses){
how can I just type something like this:
$billingAddress = $order->getRelation('billingAddresses') // check the column_id first
- note:
the original$order->billingAddresses
runs the join sql without check the column_id if its null first
2
Answers
It seems you’re misunderstanding the relation. Your
$order->billing_address_id
(a single integer column) can only point to a single relation. Theorders
table holds the reference to thebillingAddress
relation in this case.However, you are retrieving
$order->billingAddresses
(ahasMany
relation) which means in order to know if there are anybillingAddresses
, you have to check the FOREIGN tablebilling_addresses
since that (probably) holds a column namedorder_id
.In the first case you can simply see in the order object itself if you should retrieve a billingAddress by checking the local key (Laravel automagically sees this and doesn’t run a query if local key = null). In the second case, you MUST check the foreign table so there will always run a query.
You can conditionally retrieve the relation if the column
billing_address_id
is not null and the relation NOT has already been loaded.P.S: it assumes relation defined b/w
Order
andBillingAddress
models.