Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
628 views
in Technique[技术] by (71.8m points)

cakephp - Cakephp3 : using another model in a controller

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 AppController;

use AppControllerAppController;
use AppModelTableLogsTable;
use AppModelEntityUser;
use AppModelEntityLog;

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This way

use CakeORMTableRegistry;

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

more info

EDIT since 3.6 you should use

use CakeORMTableLocator

$articles = TableRegistry::getTableLocator()->get('Articles', [
    'className' => 'AppCustomArticlesTable',
    'table' => 'my_articles',
    'connection' => $connectionObject,
    'schema' => $schemaObject,
    'entityClass' => 'CustomEntityClass',
    'eventManager' => $eventManager,
    'behaviors' => $behaviorRegistry
]);

more info here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...