問題描述
我想知道是否有人可以提供幫助,因為我遇到了困難并且仍在學習 Laravel ORM.任何人都可以解釋為什么,當我運行時:
I wonder if anyone can help, as I've hit a wall and still learning Laravel ORM. Can anyone explain why, when I run:
public function locationTags(){
return $this->hasMany('AppUserHasLocationTags', 'user_id')
->join('location_tags AS lt', 'lt.id', '=', 'location_tag_id');
}
我得到了這個結果集:(剪斷了...)
I get this result set: (snipped...)
{
"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
}
]
}
這是王牌!但是,當我開始從 location_tags 連接中選擇我想要的列時,使用:
Which is ace! However, when I start to select the columns I want from the location_tags join, with:
public function locationTags(){
return $this->hasMany('AppUserHasLocationTags', 'user_id')
->join('location_tags AS lt', 'lt.id', '=', 'location_tag_id')
->select('lt.id', 'lt.name');
}
我最終得到:
{
"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": []
}
誰能解釋一下這是怎么回事?并可能指出我正確的方向來限制選擇?謝謝!
Can someone explain what's going on? And possibly point me in the right direction to limit the selects? Thanks!
更新我也試過:
$query = AppUser::with(['permissions', 'locationTags' => function($query){
$query->select('lt.id', 'lt.name');
}]);
返回相同的結果:(
推薦答案
想通了.這里的關鍵是你必須包含至少一個 Laravel 可以用來映射結果集的鍵的 select()
值.就我而言,它是 user_id
,如下所示:
Figured it out. The key here was that you must include a select()
value of at least one key that Laravel can use to map the result set. In my case it was user_id
, like so:
public function locationTags(){
return $this->hasMany('AppUserHasLocationTags', 'user_id')
->join('location_tags AS lt', 'lt.id', '=', 'location_tag_id')
->select('user_id', 'lt.name', 'location_tag_id');
}
然后返回一個更好的結果集:
Which then returns a much nicer results set:
{
"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
}
]
}
希望這對未來的人有所幫助,因為它讓我猜了好幾個小時.
Hope this helps someone out in the future, because it kept me guessing for a good couple of hours.
這篇關于Laravel 多對多 - 意外的結果集 ->select()的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!