首页 文章

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

提问于
浏览
1

我的 user tableitem table 由多对多关系相关, item table 在外表中有一些数据,例如 color table 我有一个与两者相关的数据透视表 . 我的问题是,如果我想要检索与用户相关联的所有项目,我如何通过热切加载来获取它们?

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

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

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

      echo($i->item->color)

}

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

这里的模特:

用户模型:

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

项目型号:

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

这是数据透视表的架构

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();
        });

1 回答

  • 1

    你可以简单地使用Nested Eager Loading

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

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

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

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

    我不确定基于你的代码,关系/模型是这样的,但你得到了我的观点 .

相关问题