【问题标题】:Sort data in api resource by an item按项目对 api 资源中的数据进行排序
【发布时间】:2022-01-25 13:58:29
【问题描述】:

我有这个数据库结构:

public function up()
    {
        Schema::create('skills', function (Blueprint $table) {
            $table->id();
            $table->string('name',50);
            $table->integer('level');
            $table->string('description',100);
            $table->string('rule',100)->default('main'); // main | other | lang
            $table->timestamps();
        });
    }

现在我想通过 laravel api 资源中的规则对这些数据进行排序

例如,当我调用我的 api 路由时 它应该返回这个:


data{

main [
   0 => {
       'name' : 'name',
       'level' : 'level',
       'description' : 'description',
    }
],
other [
   0 => {
       'name' : 'name',
       'level' : 'level',
       'description' : 'description',
    }
],
lang [
   0 => {
       'name' : 'name',
       'level' : 'level',
       'description' : 'description',
    }
],

}

那我该怎么办呢

我的数据库结构好吗?

ResourceCollection 比资源好?

谢谢

【问题讨论】:

    标签: laravel api filter jsonapi-resources


    【解决方案1】:

    您应该为rule 字段添加索引以获得更好的查询性能。 https://laravel.com/docs/8.x/migrations#indexes

    我认为您需要使用 QueryBuilder 的orderBy 方法来处理它。 https://laravel.com/docs/8.x/queries#ordering

    【讨论】:

    • 我使用了 groupBy() 函数,但是你的链接很有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多