[英]Laravel - hasManyThrough and eager loading, get column from related
I'm getting some weird stuff going on when trying to eager load a related model using hasManyThrough. 当尝试使用hasManyThrough加载相关模型时,出现了一些奇怪的事情。
I have a Community model which has a function called 'roommates' to get all Users that have the community id in a column called 'community', see below code. 我有一个社区模型,该模型具有一个名为“ roommates”的功能,用于在名为“ community”的列中获取所有具有社区ID的用户,请参见以下代码。
public function roommates()
{
return $this->hasManyThrough('App\User', 'App\Community', 'id', 'community');
}
Then the User model is grabbed from Auth after login and eager loads the related models, and only displaying the columns I want. 然后在登录后从Auth抓取User模型,并渴望加载相关模型,并且仅显示我想要的列。 id, name, email
身份证,姓名,电子邮件
$user = User::where('id', Auth::id())->with(['community.roommates' => function ($query)
{
$query->select('users.id', 'name', 'email');
}])->first();
However my JSON response isn't what I expected, the id that is being returned appears to be the id of the community, even though I have specified 'users.id' 但是我的JSON响应不是我期望的,返回的ID似乎是社区的ID,即使我已指定“ users.id”
{
"status": true,
"data": {
"id": 3,
"name": "Foo Bar",
"email": "test@test.com",
"community": {
"id": 1,
"owner": 3,
"title": "Home",
"created_at": "2015-10-09 08:04:05",
"updated_at": "2015-10-09 08:04:05",
"roommates": [
{
"id": 1,
"name": "Foo Bar 2",
"email": "test@test.com"
},
{
"id": 1,
"name": "Foo Bar",
"email": "test@test.com"
}
]
},
"remember_token": "tprkiNOYbBiViwQkVcJMcwU8poZ1/00Uktmy7AQ+",
"created_at": "2015-10-09 08:03:42",
"updated_at": "2015-10-10 04:56:14"
}
}
As you can see the id on both users in the roommates array is 1, however the ids of those users are 2 and 3. 如您所见,roommates数组中两个用户的ID为1,但是这些用户的ID为2和3。
Any ideas? 有任何想法吗?
I'm still feeling around with Laravel so I'm not sure where to go from here? 我还在Laravel周围,所以我不确定从这里去哪里?
Ending up working it out, 最后解决它,
I changed to use hasMany instead of hasManyThrough 我更改为使用hasMany而不是hasManyThrough
public function roommates()
{
return $this->hasMany('App\User', 'community_id', 'id')->select(['community_id', 'id', 'name', 'email']);
}
And also I needed to select the foreign key, community_id, or else I would get a blank result. 而且我还需要选择外键community_id,否则我将得到一个空白结果。
Credits to this question helping me figure it out 归功于这个问题,帮助我弄清楚了
Laravel Eager Loading - Load only specific columns Laravel急切加载-仅加载特定列
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.