php - 将 Laravel 集合排序为 ID 数组

标签 php laravel eloquent-relationship

是否可以在仍然通过关系访问的同时使用单独的 ID 数组对关系集合进行排序?

Checklist 的设置有很多 ChecklistItem,相关项的所需顺序作为属性 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->item_order 数组中的值对 $list->items 进行排序?

(我不能只在“item”表中添加一个“order”列,因为每个“list”的顺序都会改变。)

最佳答案

你可以这样做:

$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;
}

用法:

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 类中:

public function newCollection(array $models = array())
{
    return new MyCollection($models);
}

关于php - 将 Laravel 集合排序为 ID 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28118361/

相关文章:

javascript - pikaday 日期未从 php 表单发送

PHP 抓取 txt 文件中的最后 15 行

laravel - Laravel Eloquent获取结果,关系数据为空

php - Laravel orderBy 关系

php - Laravel 8 嵌套模型关系

php - 文件获取内容返回 false

PHP : how to detect row and column number from HTML table?

php - 在 REST API 中的单个请求中插入或更新多个表中的记录是否合适?

php - 在 Laravel 中获取每个用户的最新消息(行)

php - Laravel Nova - 如何从 HasMany 字段中隐藏 'Create' 按钮?