Associations do not work at all

Hello,

I have two tables:

image

I want to make association in CakePHP v3.x like this:

UsersTable.php:

<?php

namespace App\Model\Table;

use Cake\ORM\Table;

class UsersTable extends Table
{
    public function initialize(array $config)
    {
        $this->hasOne('UserRoles');
    }
}

UserRolesTable.php:

<?php

namespace App\Model\Table;

use Cake\ORM\Table;

class UserRolesTable extends Table
{
    public function initialize(array $config)
    {
        $this->belongsToMany('Users');
    }
}

What query did Cake\ORM\Query object contain. As you see no JOIN!:

SELECT Users.user_id AS `Users__user_id`,
       Users.username AS `Users__username`,
       Users.password AS `Users__password`,
       Users.user_role_id AS `Users__user_role_id`,
       Users.internet_plan_id AS `Users__internet_plan_id`
FROM users Users

And the result I get after fetch:

{
   "user_id":1,
   "username":"admin",
   "password":"abc123",
   "user_role_id":1,
   "internet_plan_id":null
}

What i want to get is:

{
   "user_id":1,
   "username":"admin",
   "password":"abc123",
   "user_role":{
      "user_role_id":1,
      "name":"ADMINISTRATOR"
   },
   "internet_plan_id":null
}

Iā€™m stuck with this issue for at least 2 hours. I tried a lot of combinations but nothing helped. Could someone help me?
Thank you in advice.

Can you post your fetching code? Perhaps you would have missed adding ->contain('Users') to find query

1 Like

@arvindh_s is right, and as you do not follow conventions you should define foreign key for the associations.
https://book.cakephp.org/3.0/en/orm/associations.html#hasone-associations

Thank you, it worked!

1 Like