我正在使用cake
PHP版本3.x.
@H_403_1@当我查询MessagesTable时,我想获取发件人和邮件接收者的用户数据.我已经在cakePHP 2中多次这样做但我无法弄清楚为什么它在版本3.x中不起作用.
@H_403_1@我有一个UsersTable和一个MessagesTable.
@H_403_1@UsersTable
$this->hasMany('Messages');@H_403_1@MessagesTable
$this->belongsTo('Users',[ 'foreignKey' => 'sender_id','propertyName' => 'Sender',]); $this->belongsTo('Users',[ 'foreignKey' => 'user_id','propertyName' => 'Receiver' ]);@H_403_1@这是我正在使用的查询
$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',]);@H_403_1@我收回了Receiver数据,但也没有收到Sender数据.任何帮助将非常感激
你的关联是错的.如果对多个关联使用相同的模型,则需要使用不同的别名和className属性(就像在CakePHP 2中一样): –
原文链接:https://www.f2er.com/php/134558.html$this->belongsTo('Sender',[ 'className' => 'Users','foreignKey' => 'sender_id','propertyName' => 'sender',]); $this->belongsTo('Receiver','foreignKey' => 'user_id','propertyName' => 'receiver' ]);@H_403_1@这是described in the docs. @H_403_1@在您的示例代码中,Receiver会覆盖User的关联,因此您只能在结果中看到Receiver模型. @H_403_1@您的查询需要是这样的: –
$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'] ]);