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

1 回答 1

2

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

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

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

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

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

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

于 2016-02-24T13:22:23.793 回答