【发布时间】:2015-05-29 11:32:58
【问题描述】:
我有 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`)
我有以下两个雄辩的方法:-
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 个查询中,以查询所有超过 1 条 Group::all() 记录吗?
【问题讨论】:
标签: php mysql laravel laravel-4 has-and-belongs-to-many