假设有一个 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)
)
然后我想选择最后一次存款在5到10天之间的网站。
最后是那些上次存款超过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/