php - Multiple Associations to the Same Model in CakePHP 3 -
i using cakephp version 3.x.
when query messagestable want users data the sender , receiver of message. have done many times in cakephp 2 cant figure out why isn't working in version 3.x.
i have userstable , messagestable.
userstable
$this->hasmany('messages');
messagestable
$this->belongsto('users', [ 'foreignkey' => 'sender_id', 'propertyname' => 'sender', ]); $this->belongsto('users', [ 'foreignkey' => 'user_id', 'propertyname' => 'receiver' ]);
this query 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 getting receiver data not sender data well. appreciated
your associations wrong. if using same model multiple associations need use different aliases , classname
property (just in cakephp 2):-
$this->belongsto('sender', [ 'classname' => 'users', 'foreignkey' => 'sender_id', 'propertyname' => 'sender', ]); $this->belongsto('receiver', [ 'classname' => 'users', 'foreignkey' => 'user_id', 'propertyname' => 'receiver' ]);
this described in docs.
in example code receiver
overwriting association user
see receiver
model in results.
your query needs 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'] ]);
Comments
Post a Comment