Laravel雄辩得到模型 [英] Laravel eloquent get model on date
问题描述
我想让指定日期创建的所有用户:
// $ date是从命令解析的Carbon实例线参数。
//我检查了它是否正确。
$ users = User :: where('created_at','>',$ date-> startOfDay())
- >其中('created_at',' ',$ date-> endOfDay())
- > get();
但是这会返回0个结果,而在数据库中有与该日期对应的行。 p>
我做错了什么?
Carbon
不像value对象那样(即它不是不可变的),所以这样:
$ date-> startOfDay();
$ date-> endOfDay();
只需修改 $ date
对象并返回回来了。就是说,传递给查询的字符串是在 PDO
在准备语句中绑定时获得的,当 $ date
已经被变更为 endOfDay
。
这意味着你只是传递对象的引用: p>
$ start === $ end; // true
所以要么使用不同的对象:
$ $ $ $ $ $ $ = User :: where('created_at','>',$ date-> copy() - > startOfDay())
- > ;其中('created_at','<',$ date-> copy() - > endOfDay())
- > get();
或只需返回您需要的字符串,而不是 Carbon
object:
$ users = User :: where('created_at','>',$ date-> startOfDay() - > toDateTimeString())
- >其中('created_at','<',$ date-> endOfDay() - > toDateTimeString())
- > get();
still, $ date
code> xxxx-xx-xx 23:59:59 timestamp,所以请记住这一点,以防万一你需要在其他地方使用这个变量。
I want to get all users created on a specified date:
// $date is a Carbon instance parsed from command line argument.
// I checked it and it is correct.
$users = User::where('created_at', '>', $date->startOfDay())
->where('created_at', '<', $date->endOfDay())
->get();
But this returns 0 results, whereas in the database there are rows that correspond to that date.
What am I doing wrong?
Carbon
doesn't behave like value object (ie. it's not immutable), so this:
$date->startOfDay();
$date->endOfDay();
simply modifies the $date
object and returns it back. That being said, the string that is passed to the query, is obtained when PDO
binds it in the prepared statement, when $date
is already mutated to endOfDay
.
It means that you just pass reference to the object:
$start === $end; // true
So either use different objects:
$users = User::where('created_at', '>', $date->copy()->startOfDay())
->where('created_at', '<', $date->copy()->endOfDay())
->get();
or simply return the string you need in place, instead of the Carbon
object:
$users = User::where('created_at', '>', $date->startOfDay()->toDateTimeString())
->where('created_at', '<', $date->endOfDay()->toDateTimeString())
->get();
still, $date
will now hold xxxx-xx-xx 23:59:59
timestamp, so keep this in mind in case you need to work with this variable somewhere else.
这篇关于Laravel雄辩得到模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!