PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, January 14, 2022

[FIXED] "IN" and "NOT IN" in CakePHP3

 January 14, 2022     cakephp-3.0, closures, php, scope, sql     No comments   

Issue

There is an example in the Cookbook:

$query = $cities->find()
   ->where(function ($exp, $q) {
      return $exp->notIn('country_id', ['AFG', 'USA', 'EST']);
});

In SQL this should be aequivalent to: WHERE country_id NOT IN ('AFG', 'USA', 'EST')

Now, I'm trying to use a variable here. Sadly, this won't work:

$query = $cities->find()
   ->where(function ($exp, $q, $variable) {
      return $exp->notIn('country_id', $variable);
});

Any ideas?


Solution

I always find the easiest way to use IN and NOT IN is as follows in CakePHP

$query = $cities->find()
   ->where(['country_id IN' => $variable])

More information on auto generating in clauses is at the following link in the book. You can also use it to cast values to the type of the column automatically. To me it is more readable as well.

https://book.cakephp.org/3.0/en/orm/query-builder.html#automatically-creating-in-clauses



Answered By - KaffineAddict
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing