有3个表:
users
:id,name
compliments
:id,name
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_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_ids并手动查询 User
表?
1 回答
您需要定义
pivot
类并将关系belongsTo
添加到user_id的pivot模型User Model
Pivot model 使用Illuminate \ Database \ Eloquent \ Relations \ Pivot;
Feth data
有关详细信息,请查看 Defining Custom Intermediate Table Models https://laravel.com/docs/5.6/eloquent-relationships#many-to-many
EDIT
正如@JonasStaudenmeir指出的那样,没有办法急切加载
pivot user
关系 . 这是另一种解决方案User Model
UserComplement model
Fetch Data
希望它可以清除你