Laravel Eloquent groupBy to return one title of each group

前端 未结 1 1142
北荒
北荒 2021-01-26 23:30

I have a very complex issue, I want to show items under one title if title is the same for every item, Im new to Laravel and dont know how to do this, I hope there is a real sou

1条回答
  •  后悔当初
    2021-01-27 00:26

    //you need to create array to store the array of items having same title.
    //i guess the item having same title also have same id.
    Then you should use order by id  not group by.
    //it will provide you the data of same id in the conitnuous queue
    //then you can use foreach loop to push the group of items in array and wrap that array with another array.
    //so that you can push that in view. then you can loop through the array in view get the desired data.
    
    //here in this method it have check if the items belongs to previous items or not using the $previousItem variable
    public function show_device_report(Request $request)
        {
            //store the overall report.
            $wholeData = [];
            //stores the individual wrapper.
            $wrapper = [];
            //getting the id for the first items in the list
            $previousItem = $datas[0]->id;
            //transforming the values before sending to the view by
            foreach ($datas as $data) {
                //store the report of every items
                $singleItem = [];
                if ($data->id == $previousItem) {
                    $id = $data->id
                    //get all the item you need and push in the array.
                    array_push($singleItem, $id, $name, $etc);
                    array_push($wrapper, $singleItem);
                } else {
                    $previousItem = $data->id;
                    array_push($wholeData, $wrapper);
                    //set the wrapper to null so that it can store the another items group in another index.
                    $wrapper= [];
            }
            return $wholeData ;
        }
    You need to modify little code according to your needs. As there is no any table structure provided by you. store the individual item in singleItem[], then store all the single items in wraper[], and all the wraper[] in wholedata[]. Send wholedata[] to the view.

    whole[
    [wrapper1[item1,item2,item3]],
    [wrapper2[item1,item2,item3,item4]],
    [wrapper3[item1,item2]],
    ]
    

    0 讨论(0)
提交回复
热议问题