cakePHP在default.ctp上显示Cart

时间:2013-01-27 14:24:40

标签: cakephp cakephp-2.2

我有一个标准的cakePHP 2.2安装,并希望在主页上显示一个购物车,这是一个cookie,存储映射到数量的productID数组。正确设置了cookie,我已经验证了这一点。

我可以从cookie数组中检索ID,现在需要从数据库中获取产品名称,价格和内容,以便将这些内容呈现给用户,而不是一串ID。

我得到的印象是我应该在AppController.php文件中执行此操作,并使用以下代码。但这给了我下面的错误。 getData()是我的ProductController.php类中的一个方法。我尝试过使用$ uses并使用$ this-> loadModel但似乎都没有用。

Product-> getData()基本上返回产品的数据库行。我将在default.ctp文件中格式化。这样做的正确方法是什么?

class AppController extends Controller {
    public $components = array('Cookie', 'Session');
    //public $uses = array('Product');

    function beforeFilter() {
        $this->loadModel('Product');
        $cookieCartVar = $this->Cookie->read('Cart');
        $this->set('cookieCart', $cookieCartVar);

        $p = array();
        if (count($cookieCartVar) > 0) {
            foreach ($cookieCartVar as $prodId => $qty) {
                $p[] = $this->Product->getData($prodId);
            }
        }
        $this->set('cookieProducts', $p);
    }       
}

Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'getData' at line 1

SQL Query: getData 

修改

这是因为我错误地尝试在ProductsController.php中设置getData()方法。我应该尝试在MODEL中创建此功能,而不是CONTROLLER。我改为使用$ this-> Product-> findById(),因为这是我想要的。

1 个答案:

答案 0 :(得分:3)

产品型号不是您的产品型号

如果在不存在的模型上调用方法,它将作为查询传递给db:

$someModel->woopWoop(); // executes `woopWoop`

错误说:

  

错误:SQLSTATE [42000]:语法错误或访问冲突:1064 SQL语法中有错误;检查与MySQL服务器版本对应的手册,以便在第1行的“getData”附近使用正确的语法

因此,使用getData调用的模型不是具有名为getData的方法的模型。

要么从插件加载模型,而是要有AppModel的实例;在这种情况下你应该这样做:

$this->loadModel('MyPlugin.Product');

或者实例是正确的类,但它没有方法getData。您只需执行以下操作即可查看:

debug(get_class($this->Product)); // outputs e.g. "Product" or "AppModel"