doufei1893 2018-11-28 05:01
浏览 54
已采纳

扁平嵌套关系按父母和儿童排序 - 可能只有雄辩?

Is this possible using eloquent alone:

// build doc tree
public function tree()
{
    $docs = app(config('lap.model.doc'))->with(['children.parent', 'children' => function ($query) {
        return $query->orderBy('order');
    }])->whereNull('parent_id')->orderBy('order')->get()->toArray();

    $docs_array = [];

    foreach ($docs as $doc)
    {
        $docs_array[] = array_except($doc, 'children');

        if ($doc['children']) {
            foreach ($doc['children'] as $child) {
                $docs_array[] = $child;
            }
        }
    }

    return $docs_array;
}

Just curious because despite this working the way I want it to, I'm wondering if there is a better solution that might already exist within the framework capacity.

  • 写回答

1条回答 默认 最新

  • douruocai4111 2018-11-28 05:50
    关注

    Something like this can be used in SQL:

    select t.*
    from t
    order by coalesce(t.parent_id, t.id), `order`
    ;
    

    i.e. The coalesce function uses id when there is no parent_id. This "clusters" the familiy of parent and children together and then rows within the family can make use of the "order" column.

    Whilst I'm inexpert at Laravel I believe orderByRaw may be used, like so:

    orderByRaw('coalesce(parent_id, id), `order`')
    

    Also see this answer

    If using a coalesce function is a problem, this alternative can be used in SQL:

    select t.*
    from t
    order by case when t.parent_id IS NULL THEN t.id else t.parent_id end, t.`order`
    ;
    

    and that case expression could be converted into an IF for use by Laravel I suspect.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题