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 [email protected]
Laravel 8 Create Events in Fullcalendar using Ajax
FullCalendar is a open-source, lightweig...How to check if a key exists in an array in PHP
Use the PHP array_key_exists() ...How to Check If a Value Exists in an Array in JavaScript
Use the indexOf() Method You can use...How to Upgrade to Latest Ubuntu 20.04 LTS
Ubuntu has recently released its latest...Stripe Payment Gateway integration in Django with Example
In this tutorial I'll demonstrate ho...