Multiple Associations to the Same Model in CakePHP 3

我只是一个虾纸丫 提交于 2019-12-04 11:08:49

问题


I am using cakePHP version 3.x.

When i query the MessagesTable i want to get the Users data for the the sender and the receiver of the message. I have done this many times in cakePHP 2 but i cant figure out why it isn't working in version 3.x.

i have a UsersTable and a MessagesTable.

UsersTable

$this->hasMany('Messages');

MessagesTable

$this->belongsTo('Users', [
    'foreignKey' => 'sender_id',
    'propertyName' => 'Sender',
]);
$this->belongsTo('Users', [
    'foreignKey' => 'user_id',
    'propertyName' => 'Receiver'
]);

This is the query i am using

$messages = $this->Messages->find()
        ->where(['Messages.user_id' => $this->Auth->user('id')])
        ->orwhere(['Messages.sender_id' => $this->Auth->user('id')])
        ->order(['Messages.created' => 'DESC'])
        ->contain([
            'Users.Pictures',
        ]);

I am getting the Receiver data back but not the Sender data as well. Any help would be really appreciated


回答1:


Your associations are wrong. If using the same model for multiple associations you need to use different aliases and the className property (just like in CakePHP 2):-

$this->belongsTo('Sender', [
    'className' => 'Users',
    'foreignKey' => 'sender_id',
    'propertyName' => 'sender',
]);
$this->belongsTo('Receiver', [
    'className' => 'Users',
    'foreignKey' => 'user_id',
    'propertyName' => 'receiver'
]);

This is described in the docs.

In your example code Receiver is overwriting the association for User so you only see the Receiver model in the results.

Your query then needs to be something like:-

$messages = $this->Messages->find()
    ->where(['Messages.user_id' => $this->Auth->user('id')])
    ->orwhere(['Messages.sender_id' => $this->Auth->user('id')])
    ->order(['Messages.created' => 'DESC'])
    ->contain([
        'Receivers' => ['Pictures'],
        'Senders' => ['Pictures']
    ]);



回答2:


Thank you for your help @drmonkeyninja. I have found what was wrong, all i needed to do was call the Users associations i defined in the MessagesTable, i feel so stupid now.

MessagesTable

$this->belongsTo('Sender', [
    'className' => 'Users',
    'foreignKey' => 'sender_id',
    'propertyName' => 'Sender',
]);
$this->belongsTo('Receiver', [
    'className' => 'Users',
    'foreignKey' => 'user_id',
    'propertyName' => 'Receiver'
]);

The query that works:

$messages = $this->Messages->find()
        ->where(['Messages.user_id' => $this->Auth->user('id')])
        ->orwhere(['Messages.sender_id' => $this->Auth->user('id')])
        ->order(['Messages.created' => 'DESC'])
        ->contain([
            'Sender',
            'Receiver'
        ])
    ;


来源:https://stackoverflow.com/questions/30928324/multiple-associations-to-the-same-model-in-cakephp-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!