共有3张桌子:
users
:ID,名称
compliments
:ID,名称
users_compliments
:id,compliment_id,user_id,complimentor_id
这是我的用户模型:
class User extends Model
public function sent_compliments() {
return
$this->belongsToMany(
'Compliment',
'users_compliments',
'complimentor_id',
'compliment_id'
)->withPivot('user_id');
}
如果我运行$user->sent_compliments()->get()
Illuminate\Database\Eloquent\Collection {
all: [
Compliment {
id: 2,
name: "You are smart",
pivot: Illuminate\Database\Eloquent\Relations\Pivot {
user_id: 6,
id: 99,
},
},
Compliment {
id: 52,
name: "You are funny",
pivot: Illuminate\Database\Eloquent\Relations\Pivot {
user_id: 42,
id: 186,
},
},
],
}
但这是我想要的响应(它包括实际的User模型,而不只是数据透视图中的user_id)
Illuminate\Database\Eloquent\Collection {
all: [
Compliment {
id: 2,
name: "You are smart",
pivot: Illuminate\Database\Eloquent\Relations\Pivot {
user_id: 6,
id: 99,
},
user {
id: 6,
name: "John"
}
},
Compliment {
id: 52,
name: "You are funny",
pivot: Illuminate\Database\Eloquent\Relations\Pivot {
user_id: 42,
id: 186,
},
user {
id: 42,
name: "Alex"
}
},
],
}
是否有一种方法可以使负载量大得多(例如使用With::
命令)而不是遍历数据透视表,收集user_id和手动查询User
表? >
答案 0 :(得分:2)
您需要定义pivot
类并添加关系belongsTo
来枢转user_id的模型
用户模型
public function sent_compliments() {
return
$this->belongsToMany(
'Compliment',
'users_compliments',
'complimentor_id',
'compliment_id'
)->withPivot('user_id')->using('App\UserComplement');
}
枢轴模型 使用Illuminate \ Database \ Eloquent \ Relations \ Pivot;
class UserComplement extends Pivot {
protected $table = 'users_compliments';
public function user(){
return $this->belongsTo('App\User', 'user_id');
}
}
人的数据
//if you have user instance already then
$complements = $user->sent_compliments;
//if you don't have fetched user yet then try this
$user = User::with('sent_compliments')->find($userId);
$complements = $user->sent_compliments;
foreach($complements as $complement){
dd($complement);
dd($complement->pivot->user);
}
有关详细信息,请检查此定义自定义中间表模型 https://laravel.com/docs/5.6/eloquent-relationships#many-to-many
编辑
正如@JonasStaudenmeir指出的那样,没有办法渴望加载pivot user
关系。这是另一种解决方案
用户模型
public function sent_compliments() {
return $this->hasMany(UserCompliment::class , 'complimentor_id');
}
UserComplement模型
class UserComplement extends Model {
$table = 'users_compliments';
public function complimentor() {
return $this->belongsTo(User::class , 'complimentor_id');
}
public function complement() {
return $this->belongsTo(Compliment::class , 'compliment_id');
}
public function user() {
return $this->belongsTo(User::class , 'user_id');
}
}
获取数据
$user = User::with('sent_compliments','sent_compliments.complement', 'sent_compliments.user')->find($userId);
$sentComplements = $user->sent_compliments;
foreach($sentComplements as $sentComplement){
dd($sentComplement->complement);
dd($sentComplement->user);
}
希望它可能会让您明白