Sending datas to multiple tables
I'm trying to do a chat system, I'm having troubles with it, my ideia is the following:
When the user send a message, this message has to be saved in 2 tables in my database... But it isn't working, the message is saving in only one table.
public function 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;
I'm a beginner in CakePHP, so, don't need to call me a dumb.
Thanks since now. And sorry for my bad english.
Ignoring the reason why you'd want to duplicate the data (it doesn't sound like a good thing generally speaking), the reason it doesn't work is you never saved it to the 2nd table. You need to call something at minimum like:
$resposta = $messageTable->save($messageEntity);
$messageCopy = $messageAllTable->newEntity($messageEntity);
$respostaCopy = $messageAllTable->save($messageCopy);
$this->response->body($resposta && $respostaCopy);
If you meant you want to to always automatically copy to a secondary table, then you could instead add a Behavior to the main Message Table. For example, a bare-bones version would look like:
In MessageTable.php:
namespace AppModelTable;
use CakeORMTable;
class MessageTable extends Table
{
public function initialize(array $config)
{
// Add this line
$this->addBehavior('CopyMessage');
}
}
And create a src/Model/Behavior/CopyMessageBehavior.php:
namespace AppModelBehavior;
use CakeORMBehavior;
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);
}
}
链接地址: http://www.djcxy.com/p/58836.html
上一篇: ASP.NET MVC为每个动作都输出outputcache
下一篇: 将数据发送到多个表