문제

I have a standard cakePHP 2.2 installation and wish to show a cart on the homepage, which is a cookie, storing an array of productIDs mapped to quantities. The cookie is being set correctly, I've verified that.

I can retreive the IDs from the cookie array and now need to get the product names, prices and stuff BACK from the database in order to present these to the user, rather than a string of IDs.

I get the impression that I should be doing this in my AppController.php file, and have the below code. But this gives me the error as below it. getData() IS a method in my ProductController.php class. I've tried using $uses and using $this->loadModel but neither seem to work.

Product->getData() returns basically the database line for the product. I'll format this in my default.ctp file. What's the correct way of doing this?

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 

Edit

This occurred because I was incorrectly trying to set the getData() method in ProductsController.php. I should have been trying to make this function in the MODEL, not the CONTROLLER. I changed it to use $this->Product->findById() anyway as this was what I wanted.

도움이 되었습니까?

해결책

The Product model is not your Product model

If you call a method on a model that doesn't exist, it gets passed to the db as a query:

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

The error says:

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

As such the model you are calling with getData is not a model that has a method named getData.

Either you want to load a model from a plugin, but instead have an instance of AppModel; in which case you should do:

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

Or the instance is of the correct class but it simply does not have the method getData. You can check which by simply doing:

debug(get_class($this->Product)); // outputs e.g. "Product" or "AppModel"
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top