This is the situations:
A Cart belongsTo Product. A Product belongsTo a Category.
This is my query:
$results = $this->Cart->find('all',
array(
'contain' => array(
'Product' => array('Category')
),
'conditions'=>array(
'OR' => array(
'Product.title LIKE' => "%$query%",
'Category.name LIKE' => "%$query%"
)
),
'fields'=>array('Product.title', 'Category.name'))
debug($results); exit;
The query no work !! Look at this:
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Category.name' in 'field list'
SQL Query: SELECT `Product`.`title`, `Category`.`name`, `Product`.`id` FROM `my_db`.`carts` AS `Cart` LEFT JOIN `my_db`.`products` AS `Product` ON (`Cart`.`product_id` = `Product`.`id`) WHERE ((`Product`.`title` LIKE '%apple%') OR (`Category`.`name` LIKE '%apple%'))
As you can see the Category data aren't attached to the Product !! If I try the same query with a simple condition (eg. 'Category.name LIKE' => "%$query%") the query works !! So I think that the problem is with the OR condition , but i'm unable to solve it ...
Have suggestions ?
Thx in advance
Since you're trying to OR between terms on different tables, I believe you'll have to throw out your relationship for this query and make a manual join instead. With the manual join, I think you should be able to write conditions how you want. Perhaps something like this?
$this->Cart->recursive = -1;
$results = $this->Cart->find('all',
array(
'joins' => array(
array(
'table' => 'products',
'alias' => 'Product',
'conditions' => array(
'Product.cart_id = Cart.id',
),
),
),
'conditions'=>array(
'OR' => array(
'Product.title LIKE' => "%$query%",
'Category.name LIKE' => "%$query%"
)
),
'fields'=>array('Product.title', 'Category.name'));
You are applying a condition (Category.name) that doesn't exist in the main model association (Cart and Product). I am not sure about your requirements but a good starting point is changing the query to something like this:
$results = $this->Cart->find('all',
array(
'contain' => array(
'Product' => array(
'Category' => array(
'conditions' => array('Category.name LIKE' => "%$query%"),
'fields' => array('Category.name')
)
)
),
'conditions'=>array(
'Product.title LIKE' => "%$query%"
),
'fields'=> array('Product.title')
);
Bear in mind that this is not the solution, you will have to modify the conditions according to your requirements (As you can see I removed the OR conditions)
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.