laravel 如何在laravel 5中的多对多关系中急切加载?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35601573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:17:52  来源:igfitidea点击:

how to eager load in a Many to Many relationship in laravel 5?

laraveleloquentpivotloadingeager

提问by Chriz74

My user tableand item tableare related by a many to many relationship, the item tablehas some data in foreign tables, example color tableI have a pivot table that relates the two. My question is, if I want to retrieve all the items associated to a user with a color how do I get them with eager loading?

Myuser tableitem table通过多对多关系相关,item table在外部表中有一些数据,例如color table我有一个将两者相关联的数据透视表。我的问题是,如果我想检索与具有颜色的用户关联的所有项目,我如何通过预先加载来获取它们?

I know that $user->itemwill retrieve all the items for that user.

我知道这$user->item将检索该用户的所有项目。

But if I want to eager load all the items for that user with the color attributes in one query, how do I do it? At the moment I am looping through the items associated to the user and lazy loading every data I need, for example

但是,如果我想在一个查询中使用颜色属性急切加载该用户的所有项目,我该怎么做?目前我正在遍历与用户关联的项目并延迟加载我需要的每个数据,例如

foreach($user->item as $i){

      echo($i->item->color)

}

This means every cycle makes a new query...

这意味着每个周期都会产生一个新的查询......

here the models:

这里的模型:

User model:

用户模型:

public function item(){
        return $this->belongsToMany('App\item')->withTimestamps();
    }

item model:

物品型号:

public function user(){
        return $this->belongsToMany('App\User');
    }

and this the schema for the pivot table

这是数据透视表的架构

Schema::create('item_user', function(Blueprint $table) {

            $table->unsignedInteger('user_id')->unsigned()->index();
            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');

            $table->unsignedInteger('item_id')->unsigned()->index();
            $table->foreign('item_id')
                ->references('id')
                ->on('items')
                ->onDelete('cascade');

            $table->timestamps();
        });

回答by Luceos

You can simply use a Nested Eager Loading

您可以简单地使用嵌套的急切加载

Eager loading is done using with(): in your instance you could use the following:

急切加载是使用with(): 在您的实例中完成的,您可以使用以下内容:

public function item(){
    return $this->belongsToMany('App\item')->withTimestamps()->with('color');
}

This will eager load the color on the "item". However you can also eager load immediately on the User model in your controller:

这将急切加载“项目”上的颜色。但是,您也可以立即在控制器中的 User 模型上立即加载:

User::with('items.color')->find(1);

I'm not sure based on your code that the relations/model is like this, but you get the point I guess.

根据你的代码,我不确定关系/模型是这样的,但我猜你明白了。