I have some items from a table and I want to search for each item’s id in other 4 tables (that currently have around 5k-6k rows but will be larger in the future).
$items = ItemStock::all(); foreach($items as $item) { $checklist = ChecklistItem::find($item->id); if($checklist == null) { $r_checklist = ReturningChecklistItem::find($item->id); if($r_checklist == null) { $transfer = TransferItem::find($item->id); if($transfer == null) { $consumption = ConsumptionItem::find($item->id); } } } }
I have to search through all tables (as above) and if I don’t find the item in one of the tables, I keep searching in the others. But this will not be efficient if the tables will be larger in the future.
Is there a way that can be more efficient? Also, these items will be shown in one of the pages, so I should include a loading spinner until the all the items will load (after checking in the code above). Is this a good approach?
Advertisement
Answer
I suggest read Eloquent Relationships
Then for query optimization Eager Loading
And the other form is use Inner or Left Joins For the related data to Item