Laravel:模型属性和whereBetween
Laravel: Model attribute and whereBetween
我是不是遗漏了什么,但这不起作用?我有模型属性 getEntryEndingAttribute
public function getEntryEndingAttribute ()
{
if($this->whereBetween('ending', [now(), now()->addDays(1)])) {
return TRUE;
}
return FALSE;
}
我从调试中得到的结果是
select count(*) as aggregate from `entries` where `ending` >= '2021-03-27 23:08:25'
当我从控制器做同样的事情时
$entries = Entry::whereBetween('ending', [now(), now()->addDays(1)])->orderBy('ending', 'ASC')->get();
调试结果正确
select count(*) as aggregate from `entries` where `ending` between '2021-03-27 23:10:52' and '2021-03-28 23:10:52'
有什么想法吗?
谢谢。
您处于对象和 getter 上下文中,因此您不必使用 whereBetween
。
另外,函数名不正确,应该是getEndingAttribute
。此外,您可能会寻找类似的内容:
public function getEntryEndingAttribute()
{
return $this->ending >= now() && $this->ending <= now()->addDays(1);
}
getEntryEndingAttribute
returns 模型的一个值,它在获取时不过滤条目。
whereBetween
过滤从数据库中选择的条目。
要进行过滤,您需要一个范围:
public function scopeEntryEnding($query)
{
return $query->whereBetween('ending', [now(), now()->addDays(1)]);
}
并按如下方式使用它:
$entries = Entry::entryEnding()->orderBy('ending', 'ASC')->get();
我是不是遗漏了什么,但这不起作用?我有模型属性 getEntryEndingAttribute
public function getEntryEndingAttribute ()
{
if($this->whereBetween('ending', [now(), now()->addDays(1)])) {
return TRUE;
}
return FALSE;
}
我从调试中得到的结果是
select count(*) as aggregate from `entries` where `ending` >= '2021-03-27 23:08:25'
当我从控制器做同样的事情时
$entries = Entry::whereBetween('ending', [now(), now()->addDays(1)])->orderBy('ending', 'ASC')->get();
调试结果正确
select count(*) as aggregate from `entries` where `ending` between '2021-03-27 23:10:52' and '2021-03-28 23:10:52'
有什么想法吗?
谢谢。
您处于对象和 getter 上下文中,因此您不必使用 whereBetween
。
另外,函数名不正确,应该是getEndingAttribute
。此外,您可能会寻找类似的内容:
public function getEntryEndingAttribute()
{
return $this->ending >= now() && $this->ending <= now()->addDays(1);
}
getEntryEndingAttribute
returns 模型的一个值,它在获取时不过滤条目。
whereBetween
过滤从数据库中选择的条目。
要进行过滤,您需要一个范围:
public function scopeEntryEnding($query)
{
return $query->whereBetween('ending', [now(), now()->addDays(1)]);
}
并按如下方式使用它:
$entries = Entry::entryEnding()->orderBy('ending', 'ASC')->get();