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

如何通过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.

    点赞 评论

相关推荐 更多相似问题