1

I want to do the following mysql query with the query builder of Laravel 7:

SELECT r.id, (SELECT date FROM posts as pp where r.id = pp.request_id 
ORDER BY STR_TO_DATE(SUBSTRING(pp.date, 1, 19),'%Y-%m-%dT%H:%i:%s') DESC limit 1), r.delivery_mode FROM requests AS r 
LEFT JOIN posts AS p ON r.id = p.request_id
group by r.id;

However unfortunately I don't understand how to obtain the latests post date for every request using the query builder of Laravel. I suppose I should do a subquery as in the query above. This is my code:

$query = DB::table('requests'); 
$query->select(DB::raw('DISTINCT(requests.id)'),'requests.delivery_mode',DB::raw('posts.date'));
$query->leftJoin('posts', 'requests.id', '=', 'posts.request_id');
$requests_list = $query->get();

In the table posts, the date is a string in this format: 2020-04-16T12:46:33+02:00. So I used that complicated functions because I want to see only the latest date post grouped by id_request, that is the foreign key of the table posts connected with the primary key id of the table requests. A request can have many posts.

Can help?

PS:

I found the solution:

$query = DB::table('requests'); 
$query->select(DB::raw('DISTINCT(requests.id)'),'requests.delivery_mode',DB::raw("(SELECT date FROM posts as pp where requests.id = pp.request_id ORDER BY STR_TO_DATE(SUBSTRING(pp.date, 1, 19),'%Y-%m-%dT%H:%i:%s') DESC limit 1) as lastPostDate"));
$query->leftJoin('posts', 'requests.id', '=', 'posts.request_id');
$requests_list = $query->get();

Probably it isn't a pretty solution but it works!.

4
  • 1
    Your LEFT JOIN returns regular INNER JOIN result since you have table p condition in the WHERE clause. Move to ON to get true LEFT JOIN result. Commented May 11, 2020 at 8:41
  • may I know what is the relation between request and post? line one to many or one to one, etc Commented May 11, 2020 at 8:55
  • One to many. One request can have many posts. Commented May 11, 2020 at 8:59
  • @jarlh I updated mysql query adding the left join. Is it a way to do the same with the query builder of Laravel? Commented May 11, 2020 at 10:22

1 Answer 1

1

Request Model

public function posts()
{
    return $this->hasMany(Post::class);
}

Post Model

public function request()
{
    return $this->belongsTo(Request::class); 
}

Controller

public function index()
{
   $date = Post::has("request")
               ->orderBy(...) // add your order by condition here
               ->limit(1)
               ->pluck("date");
   $requests = Request::with("posts")
                      ->where("date", $date)
                      ->get();
   return $requests; 
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.