I have 2 tables, users and roles, as follows:
USERS ROLES
-----------------------------
id id
role_id name
fname ...
...
How do I properly setup the relation between the 2?
In my mapper Users extends \flight\ActiveRecord
I have this constructor:
function __construct($databaseConnection) {
$this->relations = [
'role' => [ self::HAS_ONE, \Main\Models\Roles::class, 'id' ]
];
parent::__construct($databaseConnection, 'users');
}
Based on the docs online, when I run this code in my controller
$user = $this->mapper->find(7);
I'd expect to have $user->role->name with the name of the role assigned to user with id=7 but instead it's NULL.
To pull the correct role name I need to run the following block:
$user = $this->mapper->find(7);
$user->role->find($user->getData()['role_id'])->getData();
and only then I have the proper value in $user->role->name.
Is this how this feature is meant to work or am I doing something wrong in my mapper?
Thank you.
I think I see the issue. Based on looking at the docs here it looks like that should reference the local key rather than foreign key id.
So your code should be this:
function __construct($databaseConnection) {
$this->relations = [
'role' => [ self::BELONGS_TO, \Main\Models\Roles::class, 'role_id' ]
];
parent::__construct($databaseConnection, 'users');
}
Hope on the chat if you have any further questions!