将多个关系查询合并为一个 - laravel

Combining multiple relation query in one - laravel

我有 2 个 table:- itemsgroups

groups table 如下:-

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

items table如下:-

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`)

我有以下两种eloquent方法:-

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');
    }
}

组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');
    }
}

现在,我运行正在查询以下内容:-

$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;
    }
}

正如您在上面看到的,如果我有 10 个组,Group::find.....->items 查询将 运行 10 个查询。我可以将它们组合在 1 个查询中以获取 Group::all() 的所有超过 1 个记录吗?

您想要的是Eager Loading,这会将您的查询操作减少为两个查询。

引用 Laravel Eloquent 文档,使用您的示例:

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;
}