Laravel Eloquent 获取数据 - 判断结果集是否为
在使用 Laravel Eloquent
模型查询时,
$result = Model::where(...)->get()
你不能简单地通过以下方式判断结果集为空
if (empty($result)) { }
if (!$result) { }
if ($result) { }
因为如果你使用 dd($result);
会发现不论如何 ->get()
方法总是返回一个 Illuminate\Database\Eloquent\Collection
的实例,即使结果集为空。本质上,你的判断语句等价于 $a = new stdClass; if ($a) { ... }
,这个判断永远返回真值。
你可以在查询中通过使用 ->first()
代替 ->get()
,结果将返回第一个 Model
实例或者 null
。这在你只需要一个结果时很有用。
$result = Model::where(...)->first();
if ($result) { ... }
Notes / References
-
->first()
http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_first -
->isEmpty()
http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_isEmpty -
->count()
http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_count -
count($result)
works because the Collection implements Countable and an internalcount()
method: http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_count
补充
初接触 Laravel
的人可能会对 Collection
和 Query Builder
之间的区别感到些许困惑,因为两者有很多同名的方法,很多人也因此有时候不知道自己面对的是哪一个类。Query Builder
本质上构造了一个查询,直到你执行了某一个方法(比如 ->all()
->first()
->lists()
或者其他一些方法),它才会连接数据库执行该查询。这些方法同样存在于 Collection
的实例中,可以从查询结果中返回数据。如果你不确定自己正在面对哪一个类的实例,可以尝试 var_dump(User::all())
或者 get_class(...)
来试验真正返回的类是哪一个。我非常非常建议你查看 Collection
类的源码,它真的很简单。然后查看 Query Builder
的源码,找出哪些同名方法看看它在什么时候连接数据库进行查询。
转自
https://www.cnblogs.com/zhangwei595806165/p/5831539.html
https://douyasi.com/laravel/eloquent_collection_detect_empty.html
翻译自
https://stackoverflow.com/questions/20563166/eloquent-collection-counting-and-detect-empty