Cakephp3:在控制器中使用其他模型 [英] Cakephp3 : using another model in a controller

查看:116
本文介绍了Cakephp3:在控制器中使用其他模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用CakePHP3启动了一个应用,我需要记录一些用户的操作。因此,我已经迁移了我的日志结构,烘焙了我的控制器,模型,现在,我尝试在用户登录时获取日志。

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.

我这样更新了UsersController:

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

}

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

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

错误:在非对象上调用成员函数transactional()

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

有什么想法吗?

推荐答案

这种方式

use Cake\ORM\TableRegistry;

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

更多信息

自3.6开始,您应该使用

EDIT since 3.6 you should use

use Cake\ORM\TableLocator

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

在此处获取更多信息

这篇关于Cakephp3:在控制器中使用其他模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆