Laravel carbon 解析时间字符串失败
Laravel carbon failed to parse time string
我需要 select 模型用户中具有特定年龄的用户,但出现此错误:
DateTime::__construct(): Failed to parse time string (birth) at position 0 (b): The timezone could not be found in the database
部分控制器:
$users = User::where(Carbon::parse('birth')->diff(Carbon::now())->format('%y'), '>=', 18)->get();
当我在视图中使用它时一切正常:
@foreach ($userss as $user)
<?php $age_year = Carbon::parse($user->birth)->diff(Carbon::now())->format('%y'); ?>
@endforeach
感谢解答!
在您的控制器示例中,您试图解析字符串 'birth' 而不是数据库字段 'birth'.
由于您要返回一个集合,只需 运行 使用 filter() 方法通过返回的集合,然后再将其发送到您的视图。您还可以使用 age 属性 而不是 diff
$users = User::get()->filter(function($user, $key) {
return (Carbon::parse($user->birth)->age >= 18);
});
我没有对此进行测试,因此您可能会遇到一些拼写错误,但这就是您完成此任务的方式。
试试这个:
User::where('birth','>=', Carbon::now()->subYears(18)->toDateTimeString());
尚未测试,但希望它有效!
您可以使用 Carbon
的 diff
帮助器来计算年龄,并使用 filter
方法来过滤对象(在本例中为 User
)。
$users = User::get()->filter($user, $key) {
return Carbon\Carbon::now()->diff($user->birth)->y >= 18;
});
Carbon
还有其他可用的辅助函数,其中一些是:
// diffInYears(), diffInMonths(), diffInWeeks()
// diffInDays(), diffInWeekdays(), diffInWeekendDays()
// diffInHours(), diffInMinutes(), diffInSeconds()
请查看此内容以获取更多信息:
http://carbon.nesbot.com/docs/
我需要 select 模型用户中具有特定年龄的用户,但出现此错误:
DateTime::__construct(): Failed to parse time string (birth) at position 0 (b): The timezone could not be found in the database
部分控制器:
$users = User::where(Carbon::parse('birth')->diff(Carbon::now())->format('%y'), '>=', 18)->get();
当我在视图中使用它时一切正常:
@foreach ($userss as $user)
<?php $age_year = Carbon::parse($user->birth)->diff(Carbon::now())->format('%y'); ?>
@endforeach
感谢解答!
在您的控制器示例中,您试图解析字符串 'birth' 而不是数据库字段 'birth'.
由于您要返回一个集合,只需 运行 使用 filter() 方法通过返回的集合,然后再将其发送到您的视图。您还可以使用 age 属性 而不是 diff
$users = User::get()->filter(function($user, $key) {
return (Carbon::parse($user->birth)->age >= 18);
});
我没有对此进行测试,因此您可能会遇到一些拼写错误,但这就是您完成此任务的方式。
试试这个:
User::where('birth','>=', Carbon::now()->subYears(18)->toDateTimeString());
尚未测试,但希望它有效!
您可以使用 Carbon
的 diff
帮助器来计算年龄,并使用 filter
方法来过滤对象(在本例中为 User
)。
$users = User::get()->filter($user, $key) {
return Carbon\Carbon::now()->diff($user->birth)->y >= 18;
});
Carbon
还有其他可用的辅助函数,其中一些是:
// diffInYears(), diffInMonths(), diffInWeeks()
// diffInDays(), diffInWeekdays(), diffInWeekendDays()
// diffInHours(), diffInMinutes(), diffInSeconds()
请查看此内容以获取更多信息: http://carbon.nesbot.com/docs/