简体   繁体   中英

Combining multiple relation query in one - laravel

I have 2 tables :- items and groups

groups table as below :-

create table groups (`id` int unsigned not null auto_increment, 
                     `group_name` varchar(255), 
                      primary key(`id`)
);

items table as follows :-

create table items (`id` int unsigned not null auto_increment, 
                    `group_for` int unsigned not null, 
                    `item_name` varchar(255), 
                     primary key(`id`), 
                     key `group_for` (`group_for`), 
                     constraint `fk_group_for` foreign key (`group_for`)                  
                     references `groups`(`id`)

I have below two eloquent method :-

class Item extends \Eloquent {

    // Add your validation rules here
    public static $rules = [
        // No rules
    ];

    // Don't forget to fill this array
    protected $fillable = ['group_for', 'item_name'];


    public function divGet() {
        return $this->belongsTo('group', 'group_for', 'id');
    }
}

Group eloquent

class Group extends \Eloquent {

    // Add your validation rules here
    public static $rules = [
        // No Rules.
    ];

    // Don't forget to fill this array
    protected $fillable = ['group_name'];

    public function items() {
        return $this->hasMany('item', 'group_for', 'id');
    }
}

Now, I am running below query :-

$groupItem = array()

// Fetching all group row
$gGroup = Group::all();

// Checking if there is not 0 records
if(!is_null($gGroup)) {

    // If there are more than 1 row. Run for each row
    foreach($gGroup as $g) {
        $groupItem[] = Group::find($g->id)->items;
    }
}

As you can see above, if i have 10 groups than , Group::find.....->items query will run 10 query. Can i combine them in 1 query for all more than 1 records of Group::all() ?

What you want is Eager Loading , this will reduce your query operations into two queries.

Quoting the Laravel Eloquent docs, using your example:

Your loop will execute 1 query to retrieve all of the Groups on the table, then another query for each group to retrieve the items. So, if we have 25 groups, this loop would run 26 queries: 1 for the original group, and 25 additional queries to retrieve the items of each group.

Thankfully, we can use eager loading to reduce this operation to just 2 queries. When querying, you may specify which relationships should be eager loaded using the with method:

$groups = App\Group::with('Item')->get();
$groupItem = array();

foreach ($groups as $group) {
    $groupItem[] = $group->items;
}

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