Multiple Associations to the Same Model in CakePHP 3

后端 未结 2 1944
感动是毒
感动是毒 2021-02-09 02:18

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 tim

相关标签:
2条回答
  • 2021-02-09 02:28

    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'
            ])
        ;
    
    0 讨论(0)
  • 2021-02-09 02:43

    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']
        ]);
    
    0 讨论(0)
提交回复
热议问题