Is it possible to order a relationship collection using a separate array of ID's while still accessing through the relationship?
The setup is Checklist has many ChecklistItems and the desired order of the related items exists as a property Checklist::$item_order. It is just an array of numeric ID's in the user's desired order.
:
class Checklist extends Model {
protected $casts = ['item_order' => 'array'];
public function items() {
return $this->hasMany(ChecklistItem::class);
}
}
class ChecklistItem extends Model {
public function list() {
return $this->belongsTo(Checklist::class);
}
}
I access this relationship the normal way:
$list = Checklist::find(1234);
foreach ($list->items as $item) {
// More Code Here
}
Is there a feasible way to order $list->items based on the values in the $list->item_order array?
(I can't just add an 'order' column to the 'item' table, b/c the order changes for each 'list'.)
fieldorfind_in_setas part of your order by and just listing out values in whatever order you want. Or you could use a case statement in the select (or order) that returns numbers and order by that column. Unless laravel has another way, the only other way I can think of would be to store the items in an array and usort using your array of ids to get the desired order.$list->item_orderis ordered array of items ids??