get the latest record from leftJoin table, how to get the last record from letjoin table in laravel, in laravel whereRaw() example, nested join in join example, self join in laravel,
In this article, I will share with you one of the helpful laravel database query solutions with a simple example. we have two following tables to solve this laravel query problem.
| id | title | slug | body | tags_id | categories_id |
|----|-------|------|------|---------|---------------|
| | | | | | |
| | | | | | |
| | | | | | |
| id | article_id | comment |
|----|------------|---------|
| | | |
| | | |
Here, the challenge is to get all the records from articles
table. but, also get the latest/last comment from comments
table. here we want only new comments not all comment will get in the records.
Here we have 2 tables 'articles'
and 'comments'
where articles
is left table and comments
is the right table which has an article's comments.
We wanted to left join articles
with comments
but the join should be with the latest record from comments
table.
$query = Article::select('articles.*', 'comments.comment as article_comment')
->leftJoin('comments', function($query) {
$query->on('comments.article_id','=','articles.id')
->whereRaw('comments.id IN (select MAX(a2.id) from comments as a2 join articles as u2 on u2.id = a2.article_id group by u2.id)');
})
->get();
I hope this laravel query solution more helpful to you.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on harsukh21@gmail.com
Generate QR Code using angularx-qrcode in Angular
This article is fixated on how to engend...Get Last Inserted Record ID in PHP
Any table has id field which is AUTO_INC...How to send mail using mailtrap in laravel 7
Hey Artisan Hope you are doing...How to Convert HTML to pdf in Python
Hello guys, In this article, we will...Open a URL in a new tab in jQuery
Generally, external links into website i...