是否可以使用单独的 ID 数组来订购关系集合,同时仍然通过关系进行访问?
设置是Checklist
有很多ChecklistItem
s 以及相关项的所需顺序作为属性存在Checklist::$item_order
。它只是按用户所需顺序排列的数字 ID 数组。
:
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);
}
}
我以正常方式访问这种关系:
$list = Checklist::find(1234);
foreach ($list->items as $item) {
// More Code Here
}
有可行的订购方式吗$list->items
基于中的值$list->item_order
array?
(我不能只将“顺序”列添加到“项目”表中,因为每个“列表”的顺序都会发生变化。)
你可以这样做:
$order = $list->item_order;
$list->items->sortBy(function($model) use ($order){
return array_search($model->getKey(), $order);
}
您还可以向模型添加一个属性访问器,其作用相同
public function getSortedItemsAttribute()
{
if ( ! is_null($this->item_order)) {
$order = $this->item_order;
$list = $this->items->sortBy(function($model) use ($order){
return array_search($model->getKey(), $order);
});
return $list;
}
return $this->items;
}
Usage:
foreach ($list->sortedItems as $item) {
// More Code Here
}
如果您在多个地方需要此类功能,我建议您创建自己的 Collection 类:
class MyCollection extends Illuminate\Database\Eloquent\Collection {
public function sortByIds(array $ids){
return $this->sortBy(function($model) use ($ids){
return array_search($model->getKey(), $ids);
}
}
}
然后,实际使用该类覆盖newCollection()
在你的模型中。在这种情况下,它将位于ChecklistItems
class:
public function newCollection(array $models = array())
{
return new MyCollection($models);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)