简体   繁体   中英

How to get nested tables' data using Eloquent Relationships - Laravel?

I've two tables: 1. categories, 2. Items

Categories.php

____________
id | name
___|________
 1 | shirt
 2 | shoes

Items.php

__________________________
id | categories_id | name
___|_______________|______
 1 |   1           | casual
 2 |   1           | dress
 3 |   2           | leather
 4 |   2           | jogar

Now I want to get the data of both tables using Eloquent relationship.

Desired array:

[
  'name' => 'shirts',
  'items' => ['casual', 'dress']
],
[
   'name' => 'shoes',
   'items' => ['leather', 'jogar']
 ]

First, you need to define your relationship.

By the look of your db structure, it seems that a Category has many Items . So in this case it can be a One-to-Many or Many-to-many relationship. I'll go for the first one in this answer.

Now, in your models, define the relationship.

Category.php

public function items()
{
    return $this->hasMany(Item::class);
}

Items.php

public function category()
{
    return $this->belongsTo(Category::class);
}

Now, when querying results, you can do as simple use the with() method to eager load the relationship items

// Perform your query and load the relationship
$categories = Category::with('items')->get();

or the load() one, to lazy eager loading the related items.

// Perform your query
$categories = Category::all();
// load the related items
$categories->load('items');

Link to the documentation: Eloquent Relationships .

in your Items.php

public function category()
{
    return $this->belongsTo('App\Categories', 'foreign_key');
}

From that on just use:

$items = new Items;
$category = $items->category;

After make model Category and item you can go to Category controller and get the data from Category by

$cat = Category::all();

don not forget add

use App\Category; 

and the same thing if you want Item , Best Regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM