我试图做一个聊天系统,我遇到了麻烦,我的想法如下:
当用户发送消息时,此消息必须保存在我的数据库中的2个表中......但它不起作用,消息只保存在一个表中。
公共函数sendMessage()
$data = $this->request->data();
$sessionId = $data['idSession'];
$userId = $this->request->session()->read('Auth.User.id');
$msg = $data['message'];
$typeMessage = $data['type'];
$messageTable = TableRegistry::get('messages');
$messageAllTable = TableRegistry::get('mensage_alls');
if ($typeMessage == 1)
{
$message['session_private_id'] = $sessionId;
}
else
{
$message['session_id'] = $sessionId;
}
$message = array_merge($message, array(
'user_id' => $userId,
'message' => $msg,
'created_at' => new \DateTime(date("Y-m-d H:i:s")),
));
$messageEntity = $messageTable->newEntity();
$messageEntity = $messageTable->patchEntity($messageEntity, $message, ['validate' => false]);
$resposta = $messageTable->save($messageEntity);
$this->response->body($resposta);
return $this->response;
我是CakePHP的初学者,所以,不要叫我笨蛋。
谢谢你们。抱歉我的英语不好。
答案 0 :(得分:0)
忽略你想要复制数据的原因(一般来说听起来不是一件好事),它不起作用的原因是你从未将它保存到第二个表中。你需要至少打电话给:
$resposta = $messageTable->save($messageEntity);
$messageCopy = $messageAllTable->newEntity($messageEntity);
$respostaCopy = $messageAllTable->save($messageCopy);
$this->response->body($resposta && $respostaCopy);
如果您希望始终自动复制到辅助表,则可以在主消息表中添加Behavior。例如,一个简单的版本看起来像:
在MessageTable.php中:
namespace App\Model\Table;
use Cake\ORM\Table;
class MessageTable extends Table
{
public function initialize(array $config)
{
// Add this line
$this->addBehavior('CopyMessage');
}
}
创建 src / Model / Behavior / CopyMessageBehavior.php:
namespace App\Model\Behavior;
use Cake\ORM\Behavior;
class CopyMessageBehavior extends Behavior
{
public function copyMessage(Entity $entity)
{
$messageAllTable = TableRegistry::get('mensage_alls');
$messageCopy =messageAllTable->newEntity($messageEntity);
$messageAllTable->save($messageCopy);
}
public function beforeSave(Event $event, EntityInterface $entity)
{
$this->copyMessage($entity);
}
}