I do an app that show some products with price for register people.
When create the product page show me "Database Error"
"Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Product.utype' in 'where clause'"
My ProductsController is like this:
class ProductsController extends AppController {
public function index() {
$this->Product->recursive = 0;
$products = $this->Product->find('all');
$this->set('products', $Product);
}
/**
* view method
*
* #throws NotFoundException
* #param string $id
* #return void
*/
public function view($id = null) {
$this->Product->id = $id;
if (!$this->Product->exists()) {
throw new NotFoundException(__('Invalid Product'));
}
$this->set('products', $this->Product->read(null, $id));
}
}
And the Model Product.php is like this:
class Product extends AppModel {
public $primaryKey = 'id_prod';
/**
* belongsTo associations
*
* #var array
*/
public $belongsTo = array(
'Occurrence' => array(
'className' => 'Occurrence',
'foreignKey' => 'occurrence_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
Can help me, please?
Thank you.
Per the very explicit error:
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column
'Product.utype' in 'where clause'"
Your code is looking for the colum 'utype' in the products table (which apparently doesn't exist). If you're not sure where your code is telling it to do that, just do a project-wide search for "utype" and update it to the correct field name.
Related
I would like to create a new model using another parameter
class Beacon extends AppModel {
/**
* Display field
*
* #var string
*/
public $displayField = 'name';
/**
* Validation rules
*
* #var array
*/
public $validate = array(
'UUID' => array(
'uuid' => array(
'rule' => array('uuid'),
),
),
);
//The Associations below have been created with all possible keys, those that are not needed can be removed
/**
* hasOne associations
*
* #var array
*/
public $hasOne = array(
'Position' => array(
'className' => 'Position',
'foreignKey' => 'beacon_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
I would like to ping this beacon passing in parameter the beacon UUID not the primary key.
class Ping extends AppModel {
//The Associations below have been created with all possible keys, those that are not needed can be removed
/**
* belongsTo associations
*
* #var array
*/
public $belongsTo = array(
'Beacon' => array(
'className' => 'Beacon',
'foreignKey' => 'beacon_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
How do I create a Ping object without the beacon primary_key but the UUID ?
on the ping controller I would like to add
public function pingBeaconWithUUID($uuid) {
How do I manage that ?
Thanks !
If the UUID is unique you can use it as value for the id field. The id needs not to be an integer although it is preferable.
But I would also propose to use the approach by AgRizzo and look up the id.
i'm new in CakePHP and i'm having problems in an example i'm building to learn.
I'm building a plugin with 3 models (Categoria,Plato,Imagen)
The relationships between them are the following:
Categoria - Plato (n-n)
Plato - Imagen (1-n)
If I go to Plato view, I get all Imagen by the relationship, but when I access through a category, I can't just reach the Imagen associated with each Plato. Why? What's the problem?
Models code:
Plato:
App::uses('AppModel', 'Model');
class Plato extends ErestaurantAppModel {
public $name = 'Plato';
//public $actsAs = array('Containable');
public $hasAndBelongsToMany = array(
'Categoria' => array(
'className' => 'Categoria',
'joinTable' => 'categorias_platos',
'foreignKey' => 'plato_id',
'associationForeignKey' => 'categoria_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
)
);
public $hasMany = array('Imagen' =>
array('foreingkey' => array('plato_id')));
}
Categoria:
App::uses('AppModel', 'Model');
class Categoria extends ErestaurantAppModel {
public $name = 'Categoria';
//public $actsAs = array('Containable');
public $hasAndBelongsToMany = array(
'Plato' => array(
'className' => 'Plato',
'joinTable' => 'categorias_platos',
'foreignKey' => 'categoria_id',
'associationForeignKey' => 'plato_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
)
);
}
Imagen:
App::uses('AppModel', 'Model');
class Imagen extends ErestaurantAppModel {
public $name = 'Imagen';
//public $actsAs = array('Containable');
public $belongsTo = array('Plato');
}
Finally, the code I'm launching when i go to a Categoria view.
App::uses('AppController', 'Controller');
class CategoriasController extends ErestaurantAppController {
public $uses = array('Erestaurant.Categoria');
public function index() {
$this->Categoria->recursive = 0;
$this->set('data', $this->Categoria->find('all'));
}
public function view($id = null) {
if (!$this->Categoria->exists($id)) {
throw new NotFoundException(__('Registro inválido.'));
}
/*
$this->Categoria->recursive = -1;
$options = array('conditions' =>
array('Categoria.'.$this->Categoria->primaryKey => $id),
'contain' => array(
'Plato' => array(
'Imagen'
)
)
);
*/
$this->Categoria->recursive = 2;
$options = array('conditions' =>
array('Categoria.'.$this->Categoria->primaryKey => $id));
$this->set('item', $this->Categoria->find('first', $options));
}
}
The commented code you see it's another way I tried, using Containable, but at the end I get error "Plato is not associated with model Imagen"
Database seems all ok, with each table created as needed (categorias, platos, imagens, categorias_platos) and with all foering keys created and trying to keep CakePHP default names.
Thank you!
To access deep relations you must use containable behavior. You have a definition of containable behavior in your model, but for some reason it is commented.
public $actsAs = array('Containable');
Uppon uncommenting this line in your Categoria, you can access deep relations in this way:
$this->Categoria->find('all', array(
'contain'=>array(
'Plato.Imagen'
)
));
...or something like this. For more information plase visit this link Containable Behavior
I'm trying to set up a pretty simple website to create and edit recipes ('Recettes' in french).
I'm an experienced frontend developer with a good knowledge (not advanced) of php, and I have been working on CakePhp with a team of developers in the past. I'm kind of learning the bases of starting a project from scratch and it is really not that easy.
I've set up a project, database (Ingredients, Recette and IngredientRecette) and used Bake to generate most of the code.
I have a working CRUD workflow for my 3 models and the only thing left to do is to be able to add ingredients from the Recette/add page but i'm stuck. I followed the instructions on the cake php website (http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasmany-through-the-join-model) and other website (cause the help on cakephp's doc is really not that helpful) and I beleive I have setup a correct Hasmany Through relationship.
But the saveAll function doesn't save anything in the join model (IngredientRecette) and I've came accross a particular error (see below) after I've successfully solved another one that took me a couple of hours to work out !
So I have the feeling that I've checked, and double checked, and triple checked everything in my code and I've read every questions and answers on forums etc...
And I am stuck with this problem, maybe there is something obvious I didn't figured, or maybe and definitely don't understand how Cakephp really wordk :(
Anyway, thanks in advance for those who will be able to bring there advices or help on this :
Here is the error I get after I submitted /recettes/add (I added some form elements to add an ingredient and a quantity to my Recette) :
Warning (2): array_merge() [function.array-merge]: Argument #2 is not an array [CORE\Cake\Model\Model.php, line 2250]
Here is the array I'm passing to the saveAll() method in the controller (output from debug()):
array(
'Recette' => array(
'auteur' => '7',
'nom' => 'Nouvelle Recette',
'cout' => 'Pas cher',
'niveau' => '5',
'tps_realisation' => '30 min',
'nb_personnes' => '6',
'description' => 'Description data',
'remarque' => ''
),
'AssociatedIngredient' => array(
'id_ingredient' => '6',
'quantite' => '70 cl',
'id_recette' => '7654'
)
)
Here is my controller code :
<?php
App::uses('AppController', 'Controller');
/**
* Recettes Controller
*
* #property Recette $Recette
*/
class RecettesController extends AppController {
/**
* index method
*
* #return void
*/
public function index() {
$this->Recette->recursive = 0;
$this->set('recettes', $this->paginate());
}
/**
* view method
*
* #param string $id
* #return void
*/
public function view($id = null) {
$this->Recette->id = $id;
if (!$this->Recette->exists()) {
throw new NotFoundException(__('Invalid recette'));
}
$this->set('recette', $this->Recette->read(null, $id));
}
/**
* add method
*
* #return void
*/
public function add() {
if ($this->request->is('post')) {
debug($this->request->data);
$this->Recette->create();
if ($this->Recette->saveAll($this->request->data)) {
$this->Session->setFlash(__('The recette has been saved'));
//$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The recette could not be saved. Please, try again.'));
}
}
$this->loadModel('Ingredient');
$liste_ingr = $this->Ingredient->find('all');
$this->set('liste_ingr', $liste_ingr);
}
The IngredientRecette model
<?php
App::uses('AppModel', 'Model');
/**
* Recette Model
*
* #property IngredientRecette $ingredient
*/
class Recette extends AppModel {
/**
* Use database config
*
* #var string
*/
public $useDbConfig = 'default';
/**
* Use table
*
* #var mixed False or table name
*/
public $useTable = 'recette';
/**
* Primary key field
*
* #var string
*/
public $primaryKey = 'id_recette';
/**
* Display field
*
* #var string
*/
public $displayField = 'nom';
public $recursive = 2;
/**
* Validation rules
*
* #var array
*/
public $validate = array(
'id_recette' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
'auteur' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
'nom' => array(
'notempty' => array(
'rule' => array('notempty'),
),
),
'niveau' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
'nb_personnes' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
);
//The Associations below have been created with all possible keys, those that are not needed can be removed
/**
* hasMany associations
*
* #var array
*/
public $hasMany = array(
'AssociatedIngredient' => array(
'className' => 'IngredientRecette',
'foreignKey' => 'id_recette',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
}
And IngredientRecette model (the join model)
<?php
App::uses('AppModel', 'Model');
/**
* IngredientRecette Model
*
* #property ingredient $ingredient
* #property recette $recette
*/
class IngredientRecette extends AppModel {
/**
* Use database config
*
* #var string
*/
public $useDbConfig = 'default';
/**
* Use table
*
* #var mixed False or table name
*/
public $useTable = 'ingredient_recette';
/**
* Primary key field
*
* #var string
*/
public $primaryKey = 'id_ingredient_recette';
public $recursive = 2;
//The Associations below have been created with all possible keys, those that are not needed can be removed
/**
* belongsTo associations
*
* #var array
*/
public $belongsTo = array(
'IngredientLiaison' => array(
'className' => 'Ingredient',
'foreignKey' => 'id_ingredient',
'conditions' => '',
'fields' => '',
'order' => ''
),
'RecetteLiaison' => array(
'className' => 'Recette',
'foreignKey' => 'id_recette',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
So nothing is saved in the join model and I have this warning...
Any help appreciated and of course please let me know if anything is unclear !
thanks a lot !!
I think your data is not formatted correctly. How about trying this instead (notice the extra array I put inside Associated Ingredient). Since recipe hasMany associated ingredient, the data for Associated Ingredient should be a series of arrays.
array(
'Recette' => array(
'auteur' => '7',
'nom' => 'Nouvelle Recette',
'cout' => 'Pas cher',
'niveau' => '5',
'tps_realisation' => '30 min',
'nb_personnes' => '6',
'description' => 'Description data',
'remarque' => ''
),
'AssociatedIngredient' => array(
array(
'id_ingredient' => '6',
'quantite' => '70 cl',
'id_recette' => '7654'
),
array( /*ingredient 2 data*/ ),
)
);
I'm trying to use find('list') method, but without success.
When I try to LIST the types of paying, just one table of database was showing correct, another is doing correct SQL but it's returning me null (even with the sql get rows).
If try to read ONE field of Tpagamento, it works
If I change the displayField of Tpagamento to 'id', it works, but the query only show the id.
Here is the scenario:
(Parcelamento and Tpagamento have the same databasefields)
View Method:
public function view($id = null) {
$this->Ordemservico->id = $id;
if (!$this->Ordemservico->exists()) {
$this->Session->setFlash('This Order does not exist..','flash_error');
$this->redirect(array('action' => 'index'));
}
//Listing all orders // THIS IS WORKING
$os = $this->Ordemservico->read(null, $id);
$this->set('os',$os);
//Listing the types of paying //THIS IS WORKING
$this->loadModel('Parcelamento');
$parcelamentos = $this->Parcelamento->find('list');
$this->set('parcelamentos',$parcelamentos);
$this->loadModel('Tpagamento'); // THIS IS NOT WORKING
$tpagamento = $this->Tpagamento->find('list');
$this->set('tpagamento ',$tpagamento );
//Read a specific type of paying, WORK!
$this->loadModel('Tpagamento'); // THIS IS WORKING
$tpagamentos = $this->Tpagamento->read(null,'5');
$this->set('tpagamentos',$tpagamentos);
}
OrdemServico Model:
class Ordemservico extends AppModel {
public $displayField = 'cliente_id';
public $belongsTo = array(
'Tpagamento' => array(
'className' => 'Tpagamento',
'foreignKey' => 'tpagamento_id',
),
'Parcelamento' => array(
'className' => 'Parcelamento',
'foreignKey' => 'parcelamento_id',
),
);
}
Tpagamento Model:
class Tpagamento extends AppModel {
public $useTable = 'tpagamentos';
public $displayField = 'nome';
public $hasMany = array(
'Ordemservico' => array(
'className' => 'Ordemservico',
'foreignKey' => 'tpagamento_id',
),
);
}
Parcelamento Model:
class Parcelamento extends AppModel {
public $displayField = 'nome';
public $hasMany = array(
'Ordemservico' => array(
'className' => 'Ordemservico',
'foreignKey' => 'parcelamento_id',
),
);
}
Generated SQL DUMP:
4 SELECT `Parcelamento`.`id`, `Parcelamento`.`nome` FROM `tereza`.`parcelamentos` AS `Parcelamento` WHERE 1 = 1 5 5 0
5 SELECT `Tpagamento`.`id`, `Tpagamento`.`nome` FROM `tereza`.`tpagamentos` AS `Tpagamento` WHERE 1 = 1 4 4 0
6 SELECT `Tpagamento`.`id`, `Tpagamento`.`nome`, `Tpagamento`.`created`, `Tpagamento`.`modified` FROM `tereza`.`tpagamentos` AS `Tpagamento` WHERE `Tpagamento`.`id` = 5 LIMIT 1 1 1 0
In the Config/database.php I setted: 'encoding' => 'utf8'
The reason to work In one table and not another is because in one table (tpagamentos) I have special characters and in another not (parcelamentos).
To show two fields in a list use the following syntax:
$this->Parcelamento->find('list', array('fields' => array('id', 'other_field_name')));
I'm building an MMA (mixed martial arts) website with CakePHP. I've got a fights table in my database that has three columns at its simplest: id, fighter_a, and fighter_b.
I'm having trouble getting my head around what type of relation my Fight model would have with my Fighter module. Am I right in thinking fighter_a and fighter_b would be two hasOne relations?
I tried this with the following in my Fight model:
<?php
class Fight extends AppModel {
public $name = 'Fight';
public $hasOne = array(
'FighterA' => array(
'className' => 'Fighter',
'foreignKey' => 'fighter_a'
),
'FighterB' => array(
'className' => 'Fighter',
'foreignKey' => 'fighter_b'
)
);
}
And then this in my Fighter model:
<?php
class Fighter extends AppModel {
public $name = 'Fighter';
public $hasMany = array(
'Fight'
);
}
But this threw an error in my CakePHP application when calling $this->Fight->findById($id) (where $id was the ID of a fighter):
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Fight.fighter_id' in 'field list'
How can I link my models so that I can call all fights a fighter has been in?
Distilled from conversation under the question, the solution would be this:
Rewrite the $hasMany in your FighterModel to look like:
public $hasMany = array(
'Fight' => array(
'className' => 'Fight',
'finderQuery' => 'SELECT * FROM fights AS Fight WHERE Fight.fighter_a_id = {$__cakeID__$} OR Fight.fighter_b_id = {$__cakeID__$};'
)
);