Objects in Components

Hi,

why won’t the following lines in a component create the $user object?

$userstable = TableRegistry::getTableLocator()->get(‘Users’);
$user = $userstable->find()->contain([‘Mailboxes’])->where([‘Users.id’ => $userd]);

echo $user->mailbox->id;

I get the following Error message

Notice (8): Undefined property: Cake\ORM\Query::$mailbox [APP/Controller/Component/SysmessagesComponent.php, line 88]
Notice (8): Trying to get property ‘id’ of non-object [APP/Controller/Component/SysmessagesComponent.php, line 88]

any idea?

$user = $userstable->find()
    ->contain([‘Mailboxes’])
    ->where([‘Users.id’ => $userd]);

only returns a Query object, not an entity.
If you want the query to be executed you need to tell it so via e.g.

$usersArray = $userstable->find()
    ->contain([‘Mailboxes’])
    ->where([‘Users.id’ => $userd])
    ->toArray(); 

or in your case if the first element of the query is enough then

$user = $userstable->find()
    ->contain([‘Mailboxes’])
    ->where([‘Users.id’ => $userd])
    ->first(); 

okay thanks… i did ->first(); and it works!