preloader
學習

Laravel 5.5 Eloquent relation whereHas and whereRaw usage

Version: Laravel 5.5

Model: Post, Comment

 

Post’s columns: id, title, content, created_at, updated_at Comment’s columns: id, post_id, content, c_date, c_time, u_date, u_time

  Relation: A post has many comments and a comment belongs to a post.

The following shows how to get posts, which had been comments in recent 24 hours.

use CarbonCarbon; // use package

Post::whereHas('comments', function ($query) {
  $query->whereRaw('(u_date = ? AND u_time >= ?) OR (u_date =? AND u_time <= ?)',
      [
        $yesterday->format('Y/m/d'),
        $yesterday->format('H:i:s'),
        $now->format('Y/m/d'),
        $now->format('H:i:s')
      ]
  )}
);