gpt4 book ai didi

php - Laravel - 使用 whereHas 获取最后一行

转载 作者:行者123 更新时间:2023-12-01 22:10:23 25 4
gpt4 key购买 nike

我正在尝试获取上次用户事件的时间“created_at”,我有模型 UserUserActivity
我想获取最后的用户事件并检查该用户的最后事件是否为 3 天以发送通知,

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);
}
}

Controller

$latest_activites = User::whereHas("activites",function($query){
$query->where("created_at",">=",Carbon::now()->subDays(3));
});
$latest_activites = $latest_activites->get();

最佳答案

您应该同时预加载用户事件,然后使用基于 created_at 的子查询过滤器。调用最新的来获取最后的记录,你应该可以开始了。

$latest_activites = User::with('activites')
->where("activites",function($query){

$query->where("created_at",">=",Carbon::now()->subDays(3));

})->latest()->get();

关于php - Laravel - 使用 whereHas 获取最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48276324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com