Laravel - get last row using whereHas

前端 未结 3 945
故里飘歌
故里飘歌 2020-12-18 14:51

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 act

相关标签:
3条回答
  • 2020-12-18 15:17

    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();
    
    0 讨论(0)
  • 2020-12-18 15:19

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

      $latest_activites = User::with('activites')
                        ->where("activites",function($query){
                         .
                         .
                         .
                         .
                })->latest()->get();
    
    0 讨论(0)
  • 2020-12-18 15:25

    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();
    
    0 讨论(0)
提交回复
热议问题