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 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?