我有 2 个表:- items
和 groups
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`)
我有以下两种 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;
}
关于php - 将多个关系查询组合在一个 - laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30528536/