Hello,
I am trying to get a list of all unassigned addresses to be displayed in a combo-box for the end-user to pick via AJAX. For now I have two Models: Location and Address with the relationship of one to one.
For now I am achieving the desired result with the following function:
public function getUnassignedAddresses()
{
$addresses = Address::select(['id', 'name'])->get();
$unassigned = [];
foreach ($addresses as $address) {
if (!is_object($address->location))
{
$unassigned[] = $address;
}
}
return response()->json($unassigned);
}
Now my question is how could I do this better. Like doing it without a foreach? Is there any way to use something like a where before the get() ? so that I can use less queries? The queries that are ran now by the code are:
string 'select `id`, `name` from `addresses`' (length=36)
string 'select * from `locations` where `locations`.`address_id` = ? and `locations`.`address_id` is not null limit 1' (length=109)
where the second query is executed (repeated) for every address I have in DB. You can see where this could lead right?
Thank you in advance for your time.
On the phone so YMMV:
$addresses = Address::has('location', '=', 0)->get();
Of course. Thank you for this quick and simple solution.
Here is more info from the official docs:
http://laravel.com/docs/5.1/eloquent-relationships#querying-relations
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community