Laravel != operator in where not working

馋奶兔 提交于 2019-12-07 01:15:27

问题


This query is returning null when an object is expected.

$vow = DB::table('media_featured')->where('is_video_of_the_week', 1)->
where('video_of_week_expired', '!=', 1)->first();

CREATE TABLE `media_featured` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`media_id` int(10) unsigned DEFAULT NULL,
`is_video_of_the_week` tinyint(1) DEFAULT NULL,
`is_featured` tinyint(1) DEFAULT NULL,
`video_of_week_expired` tinyint(1) DEFAULT NULL,
`featured_expired` tinyint(1) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `media_featured_media_id_foreign` (`media_id`),
CONSTRAINT `media_featured_media_id_foreign` FOREIGN KEY (`media_id`) REFERENCES `media`        (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

A record might have is_video_of_the_week = 1 and video_of_week_expired = NULL but the above query returns null.

Any ideas?


回答1:


NULL values are not equal or not equal to anything else.

So column != NULL is always falsy as well as column = NULL

To check if a column contains NULL value you need to use IS NULL operator.

In case of laravel db query generator you could use

->whereNull('video_of_week_expired')

method.

PS: if video_of_week_expired is assumed to be a flag-alike column, you better make it NOT NULL and use 0/1 values, instead of NULL/1




回答2:


If the value for video_of_week_expired is NULL or 1 then you can use

->whereNull()

else if the value is like a flag 0 or 1 then you can try using

->where('video_of_week_expired', '<>', 1)

Here <> is a 'not equal to' operator.




回答3:


Based on the documentation and the source-code.

You should use whereNull:

$vow = DB::table('media_featured')
          ->where('is_video_of_the_week', 1)
          ->whereNull('video_of_week_expired')
          ->first();


来源:https://stackoverflow.com/questions/23260171/laravel-operator-in-where-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!