Cakephp3 : using another model in a controller

萝らか妹 提交于 2019-12-18 07:26:06

问题


I started an app with CakePHP3 and i need to record some users's actions. So, I have migrated my log structure, I have baked my controller & model and now, I try to get a log when a user log in.

I updated my UsersController like this:

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']);
    }

}

But it doesn't work, I have the error message for the save() :

Error: Call to a member function transactional() on a non-object

Any ideas?


回答1:


This way

use Cake\ORM\TableRegistry;

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

more info



来源:https://stackoverflow.com/questions/37030044/cakephp3-using-another-model-in-a-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!