本文介紹了Laravel - 使用 whereHas 獲取最后一行的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在嘗試獲取最后一次用戶活動的時間created_at",我有模型 User
和 UserActivity
.
我想獲取最后一個用戶活動并檢查該用戶的最后一個活動是否是 3 天才能發(fā)送通知,
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 IlluminateDatabaseEloquentModel;
class User extends Model
{
public function activites()
{
return $this->hasMany(Activty::class);
}
}
Activity.php
<?php
namespace App;
use IlluminateDatabaseEloquentModel;
use CarbonCarbon;
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
模型中創(chuàng)建另一個關系,即 必須是 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 獲取最后一行的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!