繁体   English   中英

在一个中组合多个关系查询-Laravel

[英]Combining multiple relation query in one - laravel

我有2张桌子:- itemsgroups

groups表如下:

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

items表如下:

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

我有以下两种雄辩的方法:

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

团队雄辩

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文档:

您的循环将执行1个查询以检索表上的所有组,然后对每个组执行另一个查询以检索项目。 因此,如果我们有25个组,则此循环将运行26个查询:1个用于原始组,另外25个附加查询来检索每个组的项目。

值得庆幸的是,我们可以使用紧急加载将此操作减少为仅2个查询。 查询时,可以使用with方法指定要加载哪些关系:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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