【问题标题】:Combining multiple relation query in one - laravel将多个关系查询合二为一 - laravel
【发布时间】:2015-05-29 11:32:58
【问题描述】:

我有 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 个查询中,以查询所有超过 1 条 Group::all() 记录吗?

【问题讨论】:

    标签: php mysql laravel laravel-4 has-and-belongs-to-many


    【解决方案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;
    }
    

    【讨论】:

    • 它没有返回像“组名”这样的组数据,它只返回了所有的“项目列表”。我还想在他们的项目列表中包含像“组名”这样的组数据..
    • 你能说得更具体点吗?这与您的代码完全相同。 $group 变量包含您的组数据
    • 是的,你是对的,但就我而言,我的意思是,我有不同的情况。具有 id - 1、名称为“stackoverflow”并具有项目 abc 的组。所以它只返回abc,但它不返回,group namestackoverflow,这些项目所属的是id。仅接收ab 作为数组很难理解,这些列表属于哪个idgroup name。我希望你明白我的意思???在我上面的查询中,我可以保存另一个组数据数组。但在您的查询中,我无法获取“组”数据。
    • 只需这样做,忘记 foreach $groupItem = App\Group::with('Item')->get();
    • 天哪!我怎么能错过:) 太好了。非常感谢。我没注意到,$groupItem[0]->items[0]$groupItem[0] :) 兄弟帮了大忙。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    • 2019-01-04
    • 1970-01-01
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多