You can try to set up relationships that return results in the order for which you are looking. You should still be able to load relationships and have the results in that order. It is all assumed that the item_order field is a list of strings with a comma identifier.
public function itemsOrdered() { return $this->items() ->select('checklist_items.*') ->join('checklists', 'checklist_items.checklist_id', '=', 'checklists.id') ->orderByRaw('FIND_IN_SET(checklist_items.id, checklists.item_order)'); }
Or, if you do not want to hardcode tables / fields:
public function itemsOrdered() { $orderField = 'item_order'; $relation = $this->items(); $parentTable = $relation->getParent()->getTable(); $related = $relation->getRelated(); $relatedTable = $related->getTable(); return $relation ->select($relatedTable.'.*') ->join($parentTable, $relation->getForeignKey(), '=', $relation->getQualifiedParentKeyName()) ->orderByRaw('FIND_IN_SET('.$related->getQualifiedKeyName().', '.$parentTable.'.'.$orderField.')'); }
Now you can:
$list = Checklist::with('items', 'itemsOrdered')->first(); var_export($list->item_order); var_export($list->items->lists('id')); var_export($list->itemsOrdered->lists('id'));
Just a warning: this is pretty experimental code. It works with a small amount of test data that is available to me, but I have not done anything like this in a production environment. In addition, this is checked only for HasMany relationships. If you try this exact code on BelongsToMany or something like that, you will have problems.
source share