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.

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

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条