Search code examples
query-buildercakephp-3.0contain

CakePHP 3.0 - How do I return data from a deeper contain in the correct format?


I'm working with a user's profile that has a state id in it, so I have this query:

    $user = $this->Users->find()
        ->where(['Users.id' => $this->Auth->user('id')])
        ->contain(['UserProfiles' => function ($q) {
            return $q
                ->select(['city', 'address_one', 'address_two', 'zip'])
                ->contain(['States' => function ($q) {
                return $q
                    ->select(['id']);
            }]);
        }])
        ->select('first_name', 'last_name')
        ->first();

This returns all of my data correctly except for States - instead, I get this back:

state {"id":6}

It was a little odd, so on the front end I tried:

echo $user->user_profile->state; // yields the string {"id": 6}
echo $user->user_profile->state->id; // error: trying to access property of non-object
echo $user->user_profile->state['id']; // index error, doesn't exist

So what's the deal? Why is this returned in this fashion? I don't have anything on the column specifying it as json or anything strange; just normal cake-baked objects. How do I spit out the id?


Solution

  • I found the issue thanks to the comments. Although I was saving the id in state_id and containing based on that column, an old column that wasn't deleted yet (states) was a text field and messed up the return value of the states contain, since the contain was also named 'state.'

    I went into the database, renamed 'state' to 'old_state', and the ids again return in the standard format.