I am just making sure if I am making any mistakes. I am trying to access a function of a Model(Cart) from a different Controller(Product).
I got idea about this from a forum, i think it is right way to do. But i am getting this error
Unknown method addToCart
Can you please let me know where did i make mistake?
ProductController:
public function initialize(){
parent::initialize();
$table = $this->loadModel('Cart');// this works fine
}
public function addit() {
$table->addToCart();
}
Model:
class CartTable extends Table{
public function addToCart(){
echo "hello from model";
}
}
Is there anything i need to do more? I did not find that helps me with this.So please wise people help me out.Thank you :)
You have to use this as following.
public function initialize(){
parent::initialize();
$this->loadModel('Cart');// this works fine
}
public function addit() {
$this->Cart->addToCart();
}
In cakephp 3 you can also lodel model by TableRegistery Just use this.
use Cake\ORM\TableRegistry;
Before using put this line on use section of controller
public function addit() {
$cart_table = TableRegistry::get('Cart');
$cart_table->addToCart();
}
You need to load your model in the method, and you do not need to assign it to a var.
public function initialize(){
parent::initialize();
}
public function addit() {
$this->loadModel('Cart');
$this->Cart->addToCart();
}
This should get you up and running.
I have the same problem...
The solutions is very simple, just add this code in your model class :
namespace App\Model\Table;
So, your model will be like this :
namespace App\Model\Table;
use Cake\ORM\Table;
class CartTable extends Table{
public function addToCart(){
echo "hello from model";
}
}
I hope this will help those who are having the same problem. Thanks
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.