我正在努力争取时间" created_at"对于最后一个用户活动,
我有模型User
和UserActivity
我想获取最后一个用户活动,并检查此用户的上一个活动是否为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);
}
}
控制器
$latest_activites = User::whereHas("activites",function($query){
$query->where("created_at",">=",Carbon::now()->subDays(3));
});
$latest_activites = $latest_activites->get();
答案 0 :(得分:3)
您应该同时使用基于created_at的子查询过滤器来加载用户活动。拨打最新信息获取最后一条记录,你应该好好去。
import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';
@Injectable()
export class ApiService {
constructor(private http: Http) {}
call(url): Observable<any> {
let username: string = 'username';
let password: string = 'password';
let headers: Headers = new Headers();
headers.append("Authorization", "Basic " + btoa(username + ":" + password));
return this.http.get(url, {headers: headers})
}
}
答案 1 :(得分:0)
主要结构:model::latest()->get()
$latest_activites = User::with('activites')
->where("activites",function($query){
.
.
.
.
})->latest()->get();
答案 2 :(得分:0)
首先,在User
模型中创建另一个关系,has to be hasOne
to get the latest activity:
public function latestActivity()
{
return $this->hasOne(Activity::class)->latest();
}
然后只加载最新活动超过3天的用户
$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();