Posted at

[CakePHP 2.3.9]'column <>' => $valueで期待する動作をしない事があったので次の3パターンを試す

More than 3 years have passed since last update.


検証


$valueがscalarの場合(問題ない)


  • 問題なく動作する。

$value = 1;

$this->Comment->find('all', array(
'conditions' => array(
'id <>' => $value,
),
));


  • 次のようなSQLができた。

SELECT "Comment"."id" AS "Comment__id"

FROM "public"."comments" AS "Comment"
WHERE "id" <> 1


$valueがarrayで2件以上含まれる場合(問題ない)


  • 問題なく動作する。

$value = array(2, 3);

$this->Comment->find('all', array(
'conditions' => array(
'id <>' => $value,
),
));


  • 次のようなSQLができた。

SELECT "Comment"."id" AS "Comment__id"

FROM "public"."comments" AS "Comment"
WHERE "id" NOT IN (2, 3)


$valueがarrayで1件のみ含まれる場合(問題あり)


  • 問題が生じて動作しない。

$value = array(4);

$this->Comment->find('all', array(
'conditions' => array(
'id <>' => $value,
),
));


  • 次のようなSQLができた。

SELECT "Comment"."id" AS "Comment__id"

FROM "public"."comments" AS "Comment"
WHERE id <> = (4)

Error: SQLSTATE[42883]: Undefined function: 7 ERROR: operator does not exist: integer <> LINE 1: ...d" FROM "public"."comments" AS "Comment" WHERE id <> = (4) ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.


'NOT' => array('column' => $value)だと安全な様子


$valueがscalarの場合

$value = 1;

$this->Comment->find('all', array(
'conditions' => array(
'NOT' => array(
'id' => $value,
),
),
));

SELECT "Comment"."id" AS "Comment__id"

FROM "public"."comments" AS "Comment"
WHERE NOT ("id" = 1)


$valueがarrayで2件以上含まれる場合

$value = array(2, 3);

$this->Comment->find('all', array(
'conditions' => array(
'NOT' => array(
'id' => $value,
),
),
));

SELECT "Comment"."id" AS "Comment__id"

FROM "public"."comments" AS "Comment"
WHERE NOT ("id" IN (2, 3))


$valueがarrayで1件のみ含まれる場合

$value = array(4);

$this->Comment->find('all', array(
'conditions' => array(
'NOT' => array(
'id' => $value,
),
),
));

SELECT "Comment"."id" AS "Comment__id"

FROM "public"."comments" AS "Comment"
WHERE NOT (id = (4))