In this article i will share with you one of the helpful laravel database query solution with simple example. we have two following tables for solve this laravel query problem.
| id | title | slug | body | tags_id | categories_id |
|----|-------|------|------|---------|---------------|
| | | | | | |
| | | | | | |
| | | | | | |
| id | article_id | comment |
|----|------------|---------|
| | | |
| | | |
Here, chalange is get all the records from articles
table. but, also get the latest/last comment from comments
table. here we want only new comments not the all comment will get in the records.
Here we have 2 tables 'articles'
and 'comments'
where articles
is left table and comments
is right table which has 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
How to Detect Change in a Text Input Box in jQuery
Use the input Event You can bind the&...Show Image Preview Before Upload In jQuery Bootstrap Example
Today, Laravelcode share one helpfull tu...How to find character in string php
You can use the PHP strpos() f...How to get the value of a textarea in jQuery
Use the jQuery val() method You can u...How to show and hide div elements based on dropdown selection in jQuery
Use the jQuery change() method The fo...