我的user table
和item 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();
});