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() ?
Aucun commentaire:
Enregistrer un commentaire