Home > OS >  How to merge categories table with items table and returtn array of each category with items
How to merge categories table with items table and returtn array of each category with items

Time:12-20

I have three tables and after each table is the defined eloquent relationship of each entity.

categories

id name
1 cars
2 bikes
 public function items()
    {
        return $this->belongsToMany(AccountItem::class, "category_item", "category_id", "item_id");
    }

category_items

id category_id item_id
1 1 1
2 1 2

items

id name
1 volks
2 bmw
public function categories()
    {
        return $this->belongsToMany(Category::class, "category_items", "item_id", "category_id");
    }

I am stuck on how to get a function that will return an array of the data with each category and the corresponding items. Incase the category has null items it returns a empty array of the category.

CodePudding user response:

I assume your relationship is correct. If so, you can do this to load.

$categories = Category::with('items')->get();

foreach ($categories as $category) {
    $categoryArray = [
        'id' => $category->id,
        'name' => $category->name,
        'items' => $category->items->toArray()
    ];
}
  • Related