在仍然通过关系进行访问时,是否可以使用单独的ID数组来订购关系集合?

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?

(我不能只在"项目"表中添加"订单"列,b/c每个"列表"的订单都会更改.)

推荐答案

你可以这样做:

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

If you need this sort of functionality in multiple places I suggest you create your own Collection class:

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

Laravel相关问答推荐

在Laravel Sail Docker环境中的PHPMyAdmin中出现`Out of Memory‘错误

LARAVEL 从多个表中获取重复的行

Laravel 9 上的数组差异助手

Laravel 9 如何将 url 中的参数从一个控制器传递到另一个控制器?

如何在 Laravel 的外部 js 文件中包含 csrf_token()?

使用命令行界面停止 laravel 服务器

Laravel:如何强制使用 HTTPS?

用户''@'localhost'对数据库'forge'的访问被拒绝随机出现

如何使用 Laravel Passport 在 API 中正确实现 OAuth?

在 laravel 5 中的表单请求验证后传递旧输入

磁盘 [视频] 没有配置的驱动程序

artisan 迁移错误找不到类'Doctrine\\DBAL\\Driver\\PDOMySql\\Driver'

Laravel 初学者的良好开端

如何在 php Laravel 中对关联数组进行排序

如何在不使用视图的情况下使用 Laravel 4 发送Electron邮件?

Laravel 字符串验证以允许空字符串

Laravel - DecryptException:'MAC 无效'

laravel - 无法在控制器构造函数中获取会话

Laravel 5.2 验证错误未出现在Blade中

Laravel:如何在 PhpUnit 上启用堆栈跟踪错误