I should build up an sql query from a dynamically built up form. The user will select table fileds and AND/OR logical conditions between them. So in the end I should have an SQL query like this:
WHERE (
name LIKE "%foo%"
OR name LIKE "%bar%"
)
AND (
ad = "BP"
OR ad = "SV"
)
I tried
$query
->where(['Contacts.name LIKE' => '%foo%'])
->orWhere(['Contacts.cname LIKE' => '%bar%'])
->andWhere(function($exp){
return $exp->or_(
['Contacts.ad' => 'BP'],
['Contacts.ad' => 'SV']
);
})
);
What is clearly not good as I override Contacts.ad. I tried different ways but I was unable to get the right parenthesis.
The actual problem is more complex, as it may contain more fileds, not just this two (name and ad)
I would do this:
$query->where(['Contacts.name LIKE' => '%foo%'])
->orWhere(['Contacts.cname LIKE' => '%bar%'])
->andWhere([
'OR' => [
['Contacts.ad' => 'BP'],
['Contacts.ad' => 'SV']
]
]);
Related
I have two custom post types, playlists and games. Playlists have a ACF repeater field, that contain games.
My goal: I am trying to build a simple query, that gets all playlists that DO NOT have this game listed in the repeater field AND alll playlists that are empty (do not have any repeater fields / database entries at all). I want to use the get_posts() function to achieve my goal, if possible.
My problem: I can only get the query to show ONLY the playlists that HAVE the game by using the = operator in the "game_filter" meta query compare field (but I want the opposite). If I choose the != or <> or IS NOT operator, it spits out all available posts. And if I also include my "empty_playlists" meta query, it ALWAYS shows me all playlists, no matter what operators I use, even tho it is a OR and the listed posts do have entrys.
I tried a lot but just cant get it to work. All exmaples I found were about different things, mostly about the % problem with the repeater field names and its solution. I hope someone can help me with this real quick. What am I doing wrong? Please help fellow and better coders! :-)
This is my code
$excluded_playlists_game_id = 274;
$user_id = 1;
$args = array(
'post_type' => PSiCorePostTypes::PLAYLISTS,
'author' => $user_id,
'order_by' => 'title',
'order' => 'ASC',
'suppress_filters' => false,
'meta_query' => array(
'relation' => 'OR',
'game_filter' => array(
'type' => 'NUMERIC',
'key' => 'psi_playlist_games_%_item',
'compare' => '!=',
'value' => $excluded_playlists_game_id,
),
'empty_playlists' => array(
'key' => 'psi_playlist_games_%_item',
'compare' => 'NOT EXISTS',
),
),
);
$user_playlists = get_posts( $args );
and this function for the % problem.
add_filter( 'posts_where', 'get_user_playlists_query_allow_wildcard' );
function get_user_playlists_query_allow_wildcard( $where ) {
global $wpdb;
$where = str_replace(
"meta_key = 'psi_playlist_games_%_item",
"meta_key LIKE 'psi_playlist_games_%_item",
$wpdb->remove_placeholder_escape( $where )
);
return $where;
}
I'm updating a record in this way:
Yii::$app->db->createCommand()->update('table', ['config' => json_encode($array)],
'field1 = :field1', [':field1' => $field1]
)->execute();
My aim is to add an extra condition with the AND operator but I don't know how to do it.
I've followed this example: LINK
// UPDATE (table name, column values, condition)
Yii::$app->db->createCommand()->update('user', ['status' => 1], 'age > 30')->execute();
But it doesn't show a lot of possibilities.
try this way
Yii::$app->db->createCommand()
->update('table', ['config' => json_encode($array)],
'field1 = :field1 AND field2 = :field2',[':field1' => $field1,':field2' => $field2])
->execute();
Just like an array, with each condition separated by a ,.
In your case:
Yii::$app->db->createCommand()->update(
'table',
['config' => json_encode($array)],
['field1' => $field1, 'field2' => $field2]
)->execute();
Note that with this syntax you don't need to bind params, you could specify them directly inside the array of conditions as Yii2 santizes them.
In the controller :
$budget = $this->Budget->find('first',
array('conditions' => array(
"copros_id" => $this->Session->read('Copro.id'),
"typebudgets_id" => $typebudget['Typebudget']['id'],
"exercices_id" => $this->Session->read('Exercice.id'))));
generates the sql:
SELECT `Budget`.`id`,
`Budget`.`created`,
`Budget`.`modified`,
`Budget`.`title`,
`Budget`.`statusbudgets_id`,
`Budget`.`typebudgets_id`,
`Budget`.`copros_id`,
`Budget`.`visible`,
`Budget`.`exercices_id`
FROM `default_schema`.`budgets` AS `Budget`
WHERE `Budget`.`typebudgets_id` = ('466b50a5-4736-11e6-a160-00163ee3b504')
The Model contains :
public $belongsTo = array(
'StatusBudget' => array(
'className' => 'StatusBudget',
'foreignKey' => 'statusbudgets_id'
),
'Exercice' => array(
'className' => 'Exercice',
'foreignKey' => 'exercices_id'
),
'Typebudget' => array(
'className' => 'Typebudget',
'foreignKey' => 'typebudgets_id'
),
'Copro' => array(
'className' => 'Copro',
'foreignKey' => 'copros_id'
),
);
It looks like the conditions in the find are ignored by cakephp (2) when building the query; specifying different conditions in the find give the same sql as a result. As if the conditions don't matter in fact.
Strange (for me).
Thanks
A couple of things may be happening here:
First try to clear the model cache. If you don't know how to use the cake console just delete the files in the /tmp/cache/model folders.
The table behind the Budget model does NOT have the columns you are making a reference to. Or there is a typo in their name. In that case Cake will not use them when you build your conditions.
The db table for budget has all the required columns, but the way the Table class is defined could interfere with properly reading the table structure from the database.
Thinking about Ilia Pandia's answer I tried to specify more precisly my conditions:
$budget = $this->Budget->find('first',
array('conditions' => array(
"Budget.copros_id" => $this->Session->read('Copro.id'),
"Budget.typebudgets_id" => $typebudget['Typebudget']['id'],
"Budget.exercices_id" => $this->Session>read('Exercice.id'))));
The sql generated is now what I expected:
SELECT `Budget`.`id`, ...
FROM `default_schema`.`budgets` AS `Budget`
LEFT JOIN `default_schema`.`status_budgets` AS `StatusBudget` ON (`Budget`.`statusbudgets_id` = `StatusBudget`.`id`)
LEFT JOIN `default_schema`.`exercices` AS `Exercice` ON (`Budget`.`exercices_id` = `Exercice`.`id`)
LEFT JOIN `default_schema`.`typebudgets` AS `Typebudget` ON (`Budget`.`typebudgets_id` = `Typebudget`.`id`)
LEFT JOIN `default_schema`.`copros` AS `Copro` ON (`Budget`.`copros_id` = `Copro`.`id`)
WHERE Budget.copros_id = '5af2bda8-97d0-403a-ad96-4cf1ac171864'
AND Budget.typebudgets_id = '466b50a5-4736-11e6-a160-00163ee3b504'
AND Budget.exercices_id = '5af2c13b-43d0-412f-97d9-4752ac171864' LIMIT 1
Thank you!
In my CakePHP I have ModelA which hasMany ModelB. ModelB has an int value Q.
Can I query ModelA and use containable to ensure that only those ModelB records with the maximum value for Q?
I've tried this:
$this->ModelA->contain(array(
'ModelB.Q =(SELECT MAX(ModelB.Q) FROM modelb ModelB WHERE ModelA_id = ' . $id . ')'
));
But it throws a MySQL error because CakePHP interprets the right hand side of that equality operator as a field (at least I think that's why) and so dots it.
... WHERE `Draw`.`round` =.(SELECT MAX.(`Draw`.`round`) ...
Is there a way to do this? I'd prefer not to have to drop down into $query() mode, if at all possible.
EDIT OK, after trying to follow the advice on the page that api55 suggested, I have this code:
$dbo = $this->Tournament->getDataSource();
$conditionsSubQuery['"Draw"."tournament_id"'] = $id;
$maxRounds = $dbo->buildStatement(array(
'fields' => array('MAX(Draw.round) AS prevRound'),
'table' => $dbo->fullTableName($this->Tournament->Draw),
'alias' => 'Draw',
'limit' => null,
'offset' => null,
'joins' => array(),
'conditions' => $conditionsSubQuery,
'order' => null,
'group' => null
),
$this->Tournament
);
$maxSubQuery = ' "Draw"."round" = (' . $maxRounds . ') ';
$maxSubQueryExpression = $dbo->expression($maxSubQuery);
$this->Tournament->contain(array(
'Entrant.selected = 1',
$maxSubQueryExpression
));
$tournament = $this->Tournament->read(null, $id);
But when it runs, it gives me 7 notice/warnings. The first 6 are to do with an object being passed instead of a string:
preg_match() expects parameter 2 to be string, object given
And 6 variations on this:
Object of class stdClass to string conversion
The last is less clear:
Model "Tournament" is not associated with model ""
I suspect I'm being colossally stupid, but there we go.
The contain uses conditions as a normal find, a subquery can be generated and put in conditions. So you should be able to do this as well. Try the subquery part in here and tell me how did it go ;)
This way of generating subqueries for conditions shouldn't fail :D since is the cakephp way.
If you got an error or something comment the answer to see if i can help.
I have thee following simple model:
Item belongsTo CatalogItem
CatalogItem hasMany Item, and belongsTo Section
Section hasMany CatalogItem
I'm trying to get counts of items, grouped by catalogitem, for a certain section-
the equivalent of:
SELECT catalogitem.id, count(*) FROM section LEFT JOIN catalogitem ON section.id=catalogitem.section_id LEFT JOIN item ON item.catalogitem_id=catalogitem.id WHERE section.id=5 GROUP BY catalogitem.id
So simple in sql, yet I can't get it to work with cake models. Can anyone point as to how to do it with cake models, using the model->find?
I can't get it to group by correctly or join correctly on 3 tables :(
Edit:
highly prefer to get the info in single query
Here's a longer way, "cakeish" way:
class Item extends AppModel
{
/* snip */
var $virtualFields = array('item_count' => 'count(Item.id)');
function getCountForSection($sectionId)
{
$ca = $this->Catalogitem->find
(
'all',
array
(
'fields' => array('Catalogitem.id'),
'conditions' => array('Catalogitem.section_id' => $sectionId),
'recursive' => -1
)
);
$ca = Set::extract('/Catalogitem/id', $ca);
$ret = $this->find
(
'all',
array
(
'fields' => array('Item.catalogitem_id', 'item_count'),
'conditions' => array('Item.catalogitem_id' => $ca),
'group' => array('Item.catalogitem_id'),
'recursive' => -1
)
);
return $ret;
}
}
Then simply use it in your controller:
$ret = $this->Item->getCountForSection(1);
debug($ret);
How does it work:
Define a virtual field (cake 1.3+ only AFAIK) which will count items
Fetch all the Catalogitems belonging to a Section you're interested in
Use Set::extract() to get the Catalogitems in a simple array
Use the array of Catalogitems to filter Items while counting and grouping them
NB: You don't seem to be using Cake's naming conventions in your database. This may hurt you.
Sorry, in my first answer I somehow missed your GROUP BY requirement, which was the whole point of the question, I now realize. I haven't used this yet, but I came across it recently, and it looks like it might accomplish what you are looking for: Linkable Behavior.
http://planetcakephp.org/aggregator/items/891-linkable-behavior-taking-it-easy-in-your-db
Like Containable, but works with only right and left joins, produces much more compact queries and supports GROUP BY.
http://github.com/rafaelbandeira3/linkable
#azv
Would this work for you:
$section_id = 5;
$fields = array('CatalogItem.id as CatalogItemId', 'count(*) AS SectionCount');
$conditions = array('Section.id' => $section_id);
$joins = array(
array('table' => 'catalogitem',
'alias' => 'CatalogItem',
'type' => 'LEFT',
'conditions' => array('Section.id' => 'CatalogItem.section_id')
),
array('table' => 'item',
'alias' => 'Item',
'type' => 'LEFT',
'conditions' => array('Item.catalogitem_id' => 'CatalogItem.id')
));
$data = $this->Section->find('all',
array('fields' => $fields,
'conditions' => $conditions,
'joins' => $joins,
'group' => 'CatalogItem.id',
'recursive' => -1)
);
// access your data values
foreach ($data['Section'] as $i => $datarow) {
$catalogitem_id = $datarow['CatalogItemId'];
$section_count = $datarow['SectionCount'];
}
This way you are explicitly setting your joins and doing it all in one query. See here for more info on joins in Cake:
http://book.cakephp.org/view/1047/Joining-tables
Hope this helps. All the best,
-s_r