fan*_*tly 1 php laravel eloquent laravel-5
我想知道是否有人可以提供帮助,因为我已经撞墙而且还在学习Laravel ORM.我可以解释为什么,当我跑:
public function locationTags(){
return $this->hasMany('App\UserHasLocationTags', 'user_id')
->join('location_tags AS lt', 'lt.id', '=', 'location_tag_id');
}
Run Code Online (Sandbox Code Playgroud)
我得到这个结果集:(剪断......)
{
"id": 1,
"created_at": "2015-05-13 13:04:56",
"updated_at": "2015-05-13 13:04:56",
"email": "REMOVED",
"firstname": "REMOVED",
"lastname": "REMOVED",
"location_id": 0,
"deleted_at": null,
"permissions": [],
"location_tags": [
{
"user_id": 1,
"location_tag_id": 1,
"id": 1,
"created_at": "2015-05-13 13:06:28",
"updated_at": "2015-05-13 13:06:28",
"name": "Test Tag 0",
"location_id": 1,
"deleted_at": null
},
{
"user_id": 1,
"location_tag_id": 2,
"id": 2,
"created_at": "2015-05-13 11:40:21",
"updated_at": "2015-05-13 12:56:13",
"name": "Test Tag 123",
"location_id": 1,
"deleted_at": null
}
]
}
Run Code Online (Sandbox Code Playgroud)
哪个是王牌!但是,当我开始从location_tags join中选择我想要的列时,使用:
public function locationTags(){
return $this->hasMany('App\UserHasLocationTags', 'user_id')
->join('location_tags AS lt', 'lt.id', '=', 'location_tag_id')
->select('lt.id', 'lt.name');
}
Run Code Online (Sandbox Code Playgroud)
我最终得到:
{
"id": 1,
"created_at": "2015-05-13 13:04:56",
"updated_at": "2015-05-13 13:04:56",
"email": "REMOVED",
"firstname": "REMOVED",
"lastname": "REMOVED",
"location_id": 0,
"deleted_at": null,
"permissions": [],
"location_tags": []
}
Run Code Online (Sandbox Code Playgroud)
有人可以解释发生了什么吗?并且可能指出我正确的方向来限制选择?谢谢!
更新 我也尝试过:
$query = \App\User::with(['permissions', 'locationTags' => function($query){
$query->select('lt.id', 'lt.name');
}]);
Run Code Online (Sandbox Code Playgroud)
返回相同的结果:(
弄清楚了.这里的关键是你必须包含select()Laravel可用于映射结果集的至少一个键的值.就我而言user_id,就像这样:
public function locationTags(){
return $this->hasMany('App\UserHasLocationTags', 'user_id')
->join('location_tags AS lt', 'lt.id', '=', 'location_tag_id')
->select('user_id', 'lt.name', 'location_tag_id');
}
Run Code Online (Sandbox Code Playgroud)
然后返回更好的结果集:
{
"id": 1,
"created_at": "2015-05-13 13:04:56",
"updated_at": "2015-05-13 13:04:56",
"email": "REMOVED",
"firstname": "REMOVED",
"lastname": "REMOVED",
"location_id": 0,
"deleted_at": null,
"permissions": [],
"location_tags": [
{
"user_id": 1,
"name": "Test Tag 0",
"location_tag_id": 1
},
{
"user_id": 1,
"name": "Test Tag 123",
"location_tag_id": 2
}
]
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助将来的某个人,因为它让我猜了好几个小时.
| 归档时间: |
|
| 查看次数: |
1203 次 |
| 最近记录: |