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.

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

报告相同问题?

悬赏问题

  • ¥15 有偿求苍穹外卖环境配置
  • ¥15 代码在keil5里变成了这样怎么办啊,文件图像也变了,
  • ¥20 Ue4.26打包win64bit报错,如何解决?(语言-c++)
  • ¥15 clousx6整点报时指令怎么写
  • ¥30 远程帮我安装软件及库文件
  • ¥15 关于#自动化#的问题:如何通过电脑控制多相机同步拍照或摄影(相机或者摄影模组数量大于60),并将所有采集的照片或视频以一定编码规则存放至规定电脑文件夹内
  • ¥20 深信服vpn-2050这台设备如何配置才能成功联网?
  • ¥15 Arduino的wifi连接,如何关闭低功耗模式?
  • ¥15 Android studio 无法定位adb是什么问题?
  • ¥15 C#连接不上服务器,