Laravel 5.2嵌套foreach

时间:2016-03-25 00:26:49

标签: php arrays foreach laravel-5 laravel-5.2

我有2个模型:类别和项目。我不知道如何使用嵌套数组进行foreach循环。

类别模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{

    public static function getAll() {

        $categories= Category::orderBy('id', 'ASC')->get();

        return $categories;

    }

    public function items() {

        return $this->hasMany('App\Item', 'category_id');

    }

物品型号:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{

    public static function getAll() {

        $items = Item::orderBy('id', 'DESC')->get();

        return $items;

    }

    public function category() {

        return $this->belongsTo('App\Category');

    }

}

在我的控制器中,我这样做:

foreach($categories as $category ) {

    $data['categories'][] = [
        'id' => $category ->id,
        'name' => $category ->name,
        'items_count' => ?
    ];

}

我需要得到这样的东西。

{
  "categories": [
    {
      "id": 1,
      "name": "cat_name_1",
      "items_count": 6,
         "items": [
           {
             "id": "1",
             "name": "item_name",
             "category_id": "1",
           }
          ],
    },
    {
      "id": 2,
      "name": "cat_name_1",
      "items_count": 7,
         "items": [
           {
             "id": "2",
             "name": "item_name",
             "category_id": "2",
           }
          ],
    },
    {
      "id": 3,
      "name": "cat_name_1",
      "items_count": 4,
         "items": [
           {
             "id": "3",
             "name": "item_name",
             "category_id": "3",
           }
          ],
    },
   ]
}

帮我改进代码。

1 个答案:

答案 0 :(得分:0)

试试这个:

$categories = Category::orderBy('id', 'ASC')->with('items')->get();

只有var_dump $ categories(不需要foreach循环)来查看它是否是你想要的结果