最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

flightPHP - Active Record relations issue with setup? - Stack Overflow

programmeradmin1浏览0评论

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 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.

Share Improve this question asked Nov 17, 2024 at 4:59 BiusBius 31 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 0

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!

发布评论

评论列表(0)

  1. 暂无评论