Laravel-使用whereHas获得最后一行 [英] Laravel - get last row using whereHas
本文介绍了Laravel-使用whereHas获得最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试获取上一次用户活动的时间"created_at",
我有模型User
和UserActivity
.
我想获取最后一个用户活动,并检查该用户的最后活动是否是3天才能发送通知,
I am trying to get the time "created_at" for the last user activity,
I have the model User
, and UserActivity
.
I want to get the last user activity and check if the last activity of this user is 3 days to send notification,
User.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function activites()
{
return $this->hasMany(Activty::class);
}
}
Activity.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class Activity extends Model
{
function function user(){
return $this->belongsTo(User::class);
}
}
控制器
$latest_activites = User::whereHas("activites",function($query){
$query->where("created_at",">=",Carbon::now()->subDays(3));
});
$latest_activites = $latest_activites->get();
推荐答案
首先,在User
模型中创建另一个关系,该模型成为hasOne
获得最新活动:
First, create another relationship in User
model, which has to be hasOne
to get the latest activity:
public function latestActivity()
{
return $this->hasOne(Activity::class)->latest();
}
然后仅加载具有3天以上最新活动的用户
Then load just users who have latest activities older than 3 days
$users = User::whereHas('activites', function($q) {
$q->where('created_at', '<=', now()->subDays(3));
})
->whereDoesntHave('activites', function($q) {
$q->where('created_at', '>', now()->subDays(3));
})
->with('latestActivity')
->get();
这篇关于Laravel-使用whereHas获得最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文