简体   繁体   中英

Foreign Key in 2 tables (CakePHP)

I have 3 tables: staffs, users and threads.

Both the staffs and users can create threads and a thread belongs to a user.

In thread, there is a user_id (FK - BelongsTo). The question is, How can I identify who created the thread. If I create a field called creator_id I still don't know If it's a staff or a user who created the thread.

I also tried a different approach by creating a field called creator (enum('staff', 'user)). The limitation with this method is, when I am using Thread->find(), I couldn't figure out a way to retrieve the information of the creator.

What options do I have to achieve what I want?

Do the Model Association as the following in Model for Thread. Create a field called creator_id and store the id of the user/staff who created the thread,

public $belongsTo = array(
    'Client' => array(
        'className' => 'Staff',
        'foreignKey' => 'creator_id',
        'conditions' => array('Thread.creator' => 'staff'),
        'fields' => '',
        'order' => ''
    ),
    'User' => array(
        'className' => 'User',
        'foreignKey' => 'creator_id',
        'conditions' => array('Thread.creator' => 'user'),
        'fields' => '',
        'order' => ''
    )
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM