【问题标题】:Laravel: Model attribute and whereBetweenLaravel:模型属性和 whereBetween
【发布时间】:2021-06-24 09:58:52
【问题描述】:

我是否遗漏了一些东西,但这不起作用?我有模型属性 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'

有什么想法吗?

谢谢。

【问题讨论】:

    标签: laravel eloquent model


    【解决方案1】:

    您处于对象和吸气剂上下文中,因此您不必使用whereBetween

    另外,函数名不正确,应该是getEndingAttribute。此外,您可能会寻找类似的东西:

    public function getEntryEndingAttribute()
    {
        return $this->ending >= now() && $this->ending <= now()->addDays(1);
    }
    

    【讨论】:

    • getEndingAttribute 将替换结束属性,这可能不是 OP 想要的
    【解决方案2】:

    getEntryEndingAttribute给模型返回一个值,取值时不过滤条目。

    whereBetween 在从数据库中选择条目时过滤条目。

    对于过滤,您需要一个范围:

    public function scopeEntryEnding($query)
    {
        return $query->whereBetween('ending', [now(), now()->addDays(1)]);
    }
    

    并按如下方式使用:

    $entries = Entry::entryEnding()->orderBy('ending', 'ASC')->get();
    

    【讨论】: