【问题标题】:CakePHP: create temporary table and use itCakePHP:创建临时表并使用它
【发布时间】:2019-07-11 18:21:26
【问题描述】:

我试图在 CakePHP 2.x 中创建一个临时表,但我总是收到消息“错误:调用非对象上的成员函数 query()”。

我做了一些研究并找到了解决方案,但这个对我不起作用:Create temporary table in CakePHP and load it as a Model

编辑: 以下代码现在产生不同的错误:“错误:在数据源默认值中找不到模型 DevicesCl 的表 devices_cls。”

这是我的代码:

class DevicesController extends AppController {

public $uses = array('Device','Client');

public function index(){
    $conditions = array();

    $tmpModel = 'DevicesCl';
    $tmpTable = 'devices_cls';

    $this->loadModel('DevicesCl');
    $this->DevicesCl->query("CREATE TEMPORARY TABLE IF NOT EXISTS devices_cls AS (SELECT uuid,ownerUuid,status,os,imei,updatedOn,msisdn,model FROM device)" );

由于我是 CakePHP 的新手,我需要添加一个额外的模型类吗?我不这么认为,因为这应该由临时表处理 - 对吧?

感谢您的支持!

【问题讨论】:

  • 你在使用 MySQL 吗?
  • 是的,是mysql。顺便说一句,MouradK 的分析器解决了这个问题

标签: cakephp


【解决方案1】:
class DevicesController extends AppController {

public $uses = array('Device','Client');

public function index(){
    $conditions = array();

    $tmpModel = 'DevicesCl';
    $tmpTable = 'devices_cls';

    $this->loadModel('DevicesCl');
    $this->DevicesCl->useTable=false;
    $this->DevicesCl->query("CREATE TEMPORARY TABLE IF NOT EXISTS devices_cls AS (SELECT uuid,ownerUuid,status,os,imei,updatedOn,msisdn,model FROM device)" );
    $this->DevicesCl->useTable = $tmpTable;

【讨论】:

  • with useTable = false => 告诉 cakephp DevicesCL 没有表,在 with useTable = tableName 之后,告诉 cakephp 使用了哪个表
  • 这正是临时表的问题 -> “useTable”,现在按预期运行 - 感谢您的支持
  • 最后一点:无法将数据保存到临时表,我必须创建一个模型类,禁用数据库模型检查 -> web2.0goodies.com/blog/uncategorized/…
【解决方案2】:

问题是模型“DevicesCl”还不存在。

在链接上的示例中:模型存在

所以如果你改变了

$this->DevicesCl->query(...)

$this->Model->query(...)

但我不明白你为什么需要这样的功能......我认为肯定有最好的解决方案吗?

【讨论】:

  • 不,将 DevicesCl 更改为 Model 时,我仍然遇到同样的错误。关于更好的解决方案:我稍后会在代码中使用这个临时表添加另一个表中的其他数据进行排序和分页,我没有找到更好的解决方案
  • 好的,谢谢,这已经使我前进了,但是遇到了一个新问题:我将代码修改为: $this->loadModel($tmpModel); $this->DevicesCl->query("CREATE TEMPORARY TABLE IF NOT EXISTS devices_cls ...但我没有收到:“错误:在数据源默认值中找不到模型 DevicesCl 的表 devices_cls。”所以似乎找不到临时表- 有什么想法吗?
  • 你能编辑你的帖子并发布新的PHP吗:D
  • 问题是:你调用了一个还没有表的模型,所以你必须创建你的表并在调用模型之后。使用 $this->Model->query (Model not DevicesCl) 和 $this->loadModel('Model');
  • 此更改解决为:“错误:模型模型的表模型未在数据源默认值中找到。”
【解决方案3】:

在 Cakephp 3 中,您可以执行以下操作:

Model/Table/MyTempTable.php
<?php
// ......

class MyTempTable extends Table{

    public function initDownload(){

        $connection = ConnectionManager::get('default');

        $connection->execute('CREATE TEMPORARY TABLE temptemp as (select * from refernece_db)');
        // Do your thing
    }
}


// When use the temp table, first should do: 
$this->MyTempTable->initDownload();

// Then, can use Cakephp3 Table syntax normally as if it is a normal table

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多