【发布时间】:2016-06-06 17:00:30
【问题描述】:
我的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();
});
【问题讨论】:
-
你可以展示或模特或你的关系
标签: laravel eloquent pivot loading eager