Laravel Many to many - Unexpected result set on ->select()

后端 未结 2 1954
[愿得一人]
[愿得一人] 2021-01-16 14:46

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(){
    retu         


        
2条回答
  •  隐瞒了意图╮
    2021-01-16 15:19

    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('App\UserHasLocationTags', '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.

提交回复
热议问题