Laravel - get last row using whereHas

会有一股神秘感。 提交于 2019-12-23 02:42:23

问题


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

Controller

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

回答1:


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

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



回答2:


You should eagerload user activities at the same time then with subquery filter based on created_at. Call the latest to get last record and you should be good to go.

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

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

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



回答3:


main structure: model::latest()->get()

  $latest_activites = User::with('activites')
                    ->where("activites",function($query){
                     .
                     .
                     .
                     .
            })->latest()->get();


来源:https://stackoverflow.com/questions/48276324/laravel-get-last-row-using-wherehas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!