drllqg2903 2018-11-17 03:35
浏览 285
已采纳

如何通过id的Laravel数组获取列表的记录

Currently I have two tables, the typical master - detail, what I get is an array of id's from the detail table, [1,2,3,4,5, ...], from this I want to generate a grouping to obtain the details grouped by the master

Master

public function details()
{
    return $this->hasMany('App\Models\Detail', 'detail_id');
}

Detail

public function master()
{
    return $this->belongsTo('App\Models\Master', 'master_id');
}

Id's [1,2,3,4,5..]

my attempt to get the result, but they are not grouped

return Detail::whereIn('id', $array)->with(['master' => function($query){
        $query->groupBy('name');
    }])->get();

My question, It is not a duplicate, what makes that question is to get ids which we already have, what I want is to group. It is not correct to close;)

  • 写回答

1条回答 默认 最新

  • douhanzhen8927 2018-11-18 07:37
    关注

    In summary, I don't believe that Eloquent supports groupBy (you'll have to write your own query); and you're not grouping all of the columns.

    Your query is not modifying the columns to be selected, so laravel will be selecting all of them; and as such something unique like your IDs will be breaking up the groups. You either need to be explicit about what you're selecting to enable the groups, or explicit about how to summarise the other columns.

    The examples on the docs all show customised select queries, with the exception of those specifically under the heading 'groupBy / Having', which is probably a failure of the docs.

    But note the other examples, such as this one, that applies grouping functions to all selected columns:

    $users = DB::table('users')
                 // count is a grouping function; status is grouped below
                 ->select(DB::raw('count(*) as user_count, status'))
                 ->where('status', '<>', 1)
                 ->groupBy('status')
                 ->get();
    

    Is grouping what you really want? Grouping summarises the table, for example by provided totals, or counts, or unique 'names'. If so, you'll need to modify the query manually, like the example above.

    If you just want to order them by 'name' (i.e. group them together) then you want the orderBy function. In which case, you'd modify your code as follows:

    return Detail::whereIn('id', $array)
        ->with('master')
        ->groupBy('name')
        ->get();
    

    Whilst I don't think it matters here, you may wish to consider whether name is a unique column name between the master and detail tables.

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

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化