2

I'm new to CakePHP. I have a table to keep record of user's activity by creating a log in it. The table has two columns

+----+------------+-----------+
| id | user_id    | comment   |
+----+------------+-----------+

I want to pass values from within controller like

$this->ActivityLogs->log($user_id, 'Message sent');

log is a custom function inside ActivityLogs model which will record some more data along with passed data

public function log($user_id = null, $message = null)
{ 
   ... record code goes here

   return true;
}

But couldn't get how to write insert query inside model. How can I create custom methods like this and also can anyone suggest me good resource to go through model queries and understanding.

  • Take a tour on that page https://book.cakephp.org/3.0/en/orm/saving-data.html, it may help you – beta-developper Jan 26 '17 at 18:16
  • If you would have tried to check the documentation, you would have seen this in the main sections in the left column: https://book.cakephp.org/3.0/en/core-libraries/logging.html – floriank Jan 26 '17 at 22:29

1 Answers1

1
public function log($user_id = null, $message = null){
    //I assume here that your table name is 'logs'
    $logsTable = \Cake\ORM\TableRegistry::get('Logs', array('table' => 'logs'));
    $log = $logsTable->newEntity();

    $log->user_id = $user_id;
    $log->body = $message ;

    if ($logsTable->save($log)) {
        return true;
    }
    return false;
}
beta-developper
  • 1,689
  • 1
  • 13
  • 24