php - 在 laravel 中使用 whereHas 和 Carbon

标签 php laravel

假设有一个 Website像这样的模型:

class Website extends Authenticatable
{
        protected $primaryKey = 'website_id';

        public function deposits ()
        {
            return $this->hasMany(\App\AdminDeposit::class, 'website', 'website_id');
        }

}

另一方面,有一个 AdminDepoist模型如下:

class AdminDeposit extends Model
    {
        protected $primaryKey = 'deposit_id';

        public function website ()
        {
            return $this->belongsTo(\App\Website::class, 'website', 'website_id');
        }

    }

正如您所看到的,它们之间存在一对多的关系,每个网站都可以有一些存款。

AdminDeposit模型有 created_at每次插入新存款时设置的属性。

现在我想选择距上次存款时间不到 5 天的网站。 (意味着 if(website->last_deposit <= 5 days) )

然后我想选择最后一次存款在510天之间的网站。

最后是那些上次存款超过30天的人。

我知道应该使用whereHas()Carbon 库一起,但我不知道如何?

最佳答案

创建与 get one latest 的新 hasOne 关系押金:

public function latestDeposit()
{
    return $this->hasOne(AdminDeposit::class, 'website', 'website_id')->latest();
}

Websites that is left less than 5 days from last their deposit

Website::whereHas('latestDeposit', function($q) {
    $q->where('created_at', '>', now()->subDays(5));
})->get();

Websites that their last deposit between 5 and 10 days.

Website::whereHas('latestDeposit', function($q) {
    $q->whereBetween('created_at', [now()->subDays(10), now()->subDays(5)]);
})->get();

Those that their last deposit is greater than 30 days

Website::whereHas('latestDeposit', function($q) {
    $q->where('created_at', '<', now()->subDays(30));
})->get();

关于php - 在 laravel 中使用 whereHas 和 Carbon,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48252072/

相关文章:

php - 使用模型工厂、一对一和一对多关系定义 Laravel 外键,而无需创建不必要的模型

php - Laravel 中如何避免缓存碰撞?

php - php中的命名空间和类加载

php - 下拉选择搜索字段不起作用

php - 按字母顺序排列并计数的sql语句

php - 在 Laravel Eloquent 中,为什么选择不正确(没有 where 条件)?

php - 如何在由客户分隔符分隔的单个列中一起显示两个组连接列

php - 如何在没有数据库的情况下登录Yii2?

php mysql 按日期排序(最近)

php - 如何使用一个 laravel 安装来处理子域