Laravel 您请求了 1 个项目,但只有 0 个项目可用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46825306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel You requested 1 items, but there are only 0 items available
提问by Nevermore
I am getting row's column randomly to seed database, using eloquent :
我使用 eloquent 将行的列随机获取到种子数据库:
$physician = SelectOption::where('select_option_group_id', 1)->pluck('name')->random();
it works if data exists in select_options table. But if it does not exists, it gives an error :
如果数据存在于 select_options 表中,它会起作用。但是如果它不存在,它会给出一个错误:
You requested 1 items, but there are only 0 items available.
您请求了 1 个项目,但只有 0 个项目可用。
I want to leave it empty, if it's empty.
我想把它留空,如果它是空的。
回答by Marcin Orlowski
Check if collection is not empty prior doing random()
:
在执行random()
以下操作之前检查集合是否为空:
$collection = SelectOption::where('select_option_group_id', 1)->pluck('name');
if (!$collection->isEmpty()) {
$physician = $collection->random();
} else {
...
}
回答by Alexey Mezenin
Use inRandomOrder()
instead:
使用inRandomOrder()
来代替:
$physician = SelectOption::where('select_option_group_id', 1)->inRandomOrder()->first();
$name = is_null($physician) ? 'No data available' : $physician->name;