Cakephp3:在控制器中使用另一个模型

时间:2016-05-04 14:00:44

标签: cakephp cakephp-3.0

我使用CakePHP3启动了一个应用程序,我需要记录一些用户的操作。所以,我已经迁移了我的日志结构,我已经烧掉了我的控制器和放大器。模型,现在,我尝试在用户登录时获取日志。

我像这样更新了我的UsersController:

namespace App\Controller;

use App\Controller\AppController;
use App\Model\Table\LogsTable;
use App\Model\Entity\User;
use App\Model\Entity\Log;

class UsersController extends AppController {

    public function login(){
      $this->viewBuilder()->layout('external');
      $user = $this->Users->newEntity();
      if($this->request->is('post')){
        $user = $this->Auth->identify();
        if($user){
          //DOING : enregistrement valide$log = new Log();
            $log->user_id = 1;
            $log->action = 'lorem ipsum';
            $log->target_user = 0;
            $log->target_object = 0;
            $log->comment = 'test';
            $logs = new LogsTable();
            $logs->save($log);

          $this->Auth->setUser($user);
          if($this->Auth->user('security') == 'admin'){
            return $this->redirect(['action' => 'admin_index']);
          }else{
            return $this->redirect($this->Auth->redirectUrl());
          }
        }
        //TODO : enregistrement faux
        $this->Flash->error(__('Email or password are wrong.'));
      }
      $this->set(compact('user'));
      $this->set('_serialize', ['user']);
    }

}

但它不起作用,我有save()的错误消息:

错误:在非对象

上调用成员函数transactional()

有什么想法吗?

1 个答案:

答案 0 :(得分:4)

这样

use Cake\ORM\TableRegistry;

$logs = TableRegistry::get('LogsTable');
$logs->save($log);

more info