在不影响JSON输出的情况下使用group by限制结果数量?

时间:2018-08-07 06:22:00

标签: laravel eloquent

我正在尝试通过将parent_id分组在一起来构建线程注释系统,并使用Take限制结果。

评论表

$table->increments('id');
        $table->text('content');
        $table->integer('post_id');
        $table->integer('parent_id')->index()->nullable();
        $table->string('username');
        $table->string('user_image')->default('http://lorempixel.com/60/60/people/');
        $table->timestamps();

当我不使用take()限制输出结果时,groupedBy('parent_id')

不使用take()

进行查询
$post->comments->groupBy('parent_id');

JSON Output example

使用take()

进行查询
$post->comments->take(5)->groupBy('parent_id')

当我使用take()时,它将JSON输出更改为不再包含由parent_id分组的键。

JSON Output example

如何限制结果而不影响JSON输出?

已编辑

后置控制器

public function index(Post $post)
{
   $comments = $post->comments->groupBy('parent_id');
   return $comments;
}

修改

为什么其他回复从此主题中删除?

编辑2

奇怪的是,此查询基于我设置的限制起作用。因此,如果我将限制设置为下限(例如5),则可以按正常输出和JSON的键进行分组。但是,如果我将限制设置为5,则不会获得这些密钥。请参阅上面的JSON输出:

$comments = DB::table('comments')
                    ->where('post_id',1)
                    ->orderByDesc('created_at')
                    ->limit(7)
                    ->get();

return collect($comments)->groupBy('parent_id');

1 个答案:

答案 0 :(得分:0)

这是由于<?xml version="1.0" encoding="utf-8"?> <odoo> <record id="action_work_plan_wizard_action" model="ir.actions.act_window"> <field name="name">Generate Workplan Report</field> <field name="res_model">ewonga_pta.work_plan_wizard</field> <field name="type">ir.actions.act_window</field> <field name="view_type">form</field> <field name="view_mode">form</field> <field name="view_id" ref="work_plan_wizard_form_view"/> <field name="target">new</field> </record> <record model="ir.ui.view" id="work_plan_wizard_form_view"> <field name="name">work_plan_wizard.form</field> <field name="model">ewonga_pta.work_plan_wizard</field> <field name="arch" type="xml"> <form string="Add Attendees"> <group col="4" colspan="4"> <field name="project_id"/> <field name="start_date"/> <field name="end_date"/> </group> <group col="4" colspan="4"> <footer> <button name="check_report" string="Imprimer" type="object" default_focus="1" class="oe_highlight"/> or <button string="Annuler" class="oe_link" special="cancel"/> </footer> </group> </form> </field> </record> </odoo> 用数字键处理数组的方式引起的。

在没有json_encode()的情况下,数组键为->take(5)。它们不是顺序的,因此被编码为JSON对象。

在使用[0, 1, 6, 9]的情况下,数组键为->take(5)。这些是顺序的,因此被编码为JSON数组。

您可以通过使用[0, 1]而不是null来解决无父母注释。通常,使用0表示不存在的数据也是一种更好的解决方案。

相关问题