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 MATLAB动图的问题
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名