【问题标题】:Make custom query builder method (query scope) for all models in Laravel 5.5为 Laravel 5.5 中的所有模型制作自定义查询构建器方法(查询范围)
【发布时间】:2021-11-08 22:14:04
【问题描述】:

我有多个模型,都带有时间戳。我经常使用 whereDate 来获取今天和昨天的所有行,如下所示:

ModelName::whereDate('created_at', now()->today())->get();
ModelName::whereDate('created_at', now()->yesterday())->get();

我想让它更短、更简单,比如:

ModelName::today()->get();
ModelName::yesterday()->get();

我找不到任何方法来做到这一点,所以我在文档中发现我可以制作自己的“范围”。问题是,我可以为指定的模型制作它,但我找不到一种方法来全局制作它,适用于所有模型。现在我需要在每个模型类中粘贴这个范围方法。这可行,但我需要在每个模型类中重复此代码,所以我确定这不是一个好方法。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ModelName extends Model
{


    /**
     * Custom scope (query builder method) to easy return all items from today
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeToday($query)
    {
        return $query->whereDate('created_at', now()->today());
    }


    /**
     * Custom scope (query builder method) to easy return all items from yesterday
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeYesterday($query)
    {
        return $query->whereDate('created_at', now()->yesterday());
    }
}

【问题讨论】:

  • 你知道 laravel 如何将范围函数分配给查询构建器

标签: laravel scope laravel-5.5


【解决方案1】:

您可以在特征中定义local scopes:

<?php
namespace App\Traits;

trait Scopes
{
    public function scopeToday($query)
    {
        return $query->whereDate('created_at', now()->today());
    }

    public function scopeYesterday($query)
    {
        return $query->whereDate('created_at', now()->yesterday());
    }
}

然后在您喜欢的任何模型中使用该特征:

use App\Traits\Scopes;

并使用特征:

ModelName::today()->get();
ModelName::yesterday()->get();

另一种方法是创建和扩展一个基本模型类并在那里定义范围,但我会使用一个特征。

【讨论】:

  • 注意,确保你'使用 App\Traits\Scopes;'在模型中,而不是在标题中,或者执行“使用 App\Traits\Scopes;”在标题中,并“使用范围;”在模型中。
【解决方案2】:

如果您不想更改任何模型,但仍然为所有模型获取方法,请使用 micros:

\Illuminate\Database\Eloquent\Builder::macro('test',function (){
    $this->dd();
});

现在您可以拨打AnyModel::test()

【讨论】:

    猜你喜欢
    • 2017-11-16
    • 2015-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    相关资源
    最近更新 更多