Join in laravel with case and when statement - mysql

I've following query in Mysql :
SELECT
U.* FROM
`cr_friends` AS `cf` JOIN
`users` AS `U` WHERE
`cf`.`status` = 1
AND
(
CASE
WHEN `cf`.`friend_to` = 1 THEN `cf`.`friend_from` = `U`.`id`
WHEN `cf`.`friend_from` = 1 THEN `cf`.`friend_to` = `U`.`id`
END
) GROUP BY `U`.`id` ORDER BY `cf`.`created` desc;
I'm trying to put this in laravel in following way :
$myFriendsData = DB::table('cr_friends as cf')
->where('cf.status', '=', 1)
->Join('users as U')
->select(
DB::raw(
'(
CASE WHEN cf.friend_to = ' . auth()->user()->id . ' THEN cf.friend_from = U.id END
CASE WHEN cf.friend_from = ' . auth()->user()->id . ' THEN cf.friend_to = U.id END
)'
)
)
->select('U.*')
->orderBy('U.id', 'desc')
->get();
but didnt succeed as the mysql query is perfectly working fine but this laravel query wont.
Actually What I think is, there is problem with the Join which I'm putting in laravel it asking for one more parameter but in this case I'm unable to do that.
Can you guys please guide me so that I can achieve this.
Thanks
Randheer

Provide an empty closure for join() and use whereRaw():
$myFriendsData = DB::table('cr_friends as cf')
->where('cf.status', '=', 1)
->join('users as U', function() {})
->whereRaw(
'(
CASE
WHEN cf.friend_to = ' . auth()->user()->id . ' THEN cf.friend_from = U.id
WHEN cf.friend_from = ' . auth()->user()->id . ' THEN cf.friend_to = U.id
END
)'
)
->select('U.*')
->orderBy('U.id', 'desc')
->get();

I used the DB::raw for case end statement in join in Laravel Version 5.8
DB::table('users')
->join('settings', function ($join) {
$join->on('settings.id', '=', DB::raw(case when users.type = "admin" then users.admin_setting_id else users.setting_id end'));
})
->get();

use this
$myFriendsData = DB::table('cr_friends as cf')
->Join('users as U')
->where('cf.status', '=', 1)
->where(
DB::raw(
'(
CASE WHEN cf.friend_to = ' . auth()->user()->id . ' THEN cf.friend_from = U.id END
CASE WHEN cf.friend_from = ' . auth()->user()->id . ' THEN cf.friend_to = U.id END
)'
)
)
->select('U.*')
->orderBy('U.id', 'desc')
->get();

Related

Trying to convert a query to eloquent

I have the following SQL:
SELECT arv.*
FROM article_reference_versions arv
INNER JOIN (SELECT `order`,
Max(`revision`) AS max_revision
FROM article_reference_versions
WHERE `file` = '12338-230180-1-CE.doc'
GROUP BY `file`,
`order`) AS b
ON arv.order = b.order
AND arv.revision = b.max_revision
WHERE arv.file = '12338-230180-1-CE.doc'
I need to convert this to Eloquent, so that I can properly access the data in object form. I tried doing it as such,
$s = Models\EloArticleReferenceVersion::select(
'SELECT arv.*
FROM article_reference_versions arv
INNER JOIN (
SELECT `order`, max(`revision`) as max_revision
FROM article_reference_versions
WHERE file = ? group by `file`, `order`) AS b
ON
arv.order = b.order AND arv.revision = b.max_revision
WHERE arv.file = ?',
[
'12338-230180-1-CE.doc',
'12338-230180-1-CE.doc'
])->get();
dd($s);
But I'm running into a plethora of issues, one after another. I figured it'd be easier to just convert this into an eloquent query, looking for some help with this.
DB Query to Query using Eloquent.
$query = EloArticleReferenceVersion::query()
->join(DB::raw('( SELECT `order`,Max(`revision`) AS max_revision FROM article_reference_versions WHERE `file` = '12338-230180-1-CE.doc' GROUP BY `file`, `order`) as sub_table'), function($join) {
$join->on('sub_table.order', '=', 'article_reference_versions.order');
$join->on('sub_table.max_revision ', '=', 'article_reference_versions.revision');
})
->where('article_reference_versions.file', '=', '12338-230180-1-CE.doc' )
->get();
Not Tested

Why can't this code run in CodeIgniter?

Query code:
$query = $this->db->query(
'SELECT course.*, AVG(course_review.`rating`) AS `avg_rating`
FROM course
LEFT JOIN course_review ON `course`.`id` = `course_review`.`course_id`
WHERE `course`.`course_category`= ' . $id . '
AND `course`.`approved`= 3
AND `course`.`delete_course` != 1
AND `course`.`unpublish_course` != 1
GROUP BY `course`.`id`
ORDER BY avg_rating DESC');
return $query->result()
Thanks
You can try this Query for your problem :
Query:-
$query = $this->db->query('SELECT
course.id,
AVG(course_review.rating) AS avg_rating
FROM course
LEFT JOIN course_review
ON course.id = course_review.course_id
WHERE course.course_category = ' . $id . '
AND course.approved = 3
AND course.delete_course != 1
AND course.unpublish_course != 1
GROUP BY course.id
ORDER BY avg_rating DESC');
return $query->result();

Laravel Join with Where (Case) and AND

I'm having problem converting my SQL query to laravel queries. I want to join two tables users and messages so that i can get the users that has conversation with other users.
Database Structure:
Users:
Messages:
This is my SQL query where I get what I want:
SELECT u.id, c.id, u.first_name, u.last_name FROM messages c, users u
WHERE (CASE WHEN c.user_one = #USERID THEN c.user_two = u.ID WHEN c.user_two = #USERID THEN c.user_one= u.id END )
AND ( c.user_one = #USERID OR c.user_two = #USERID ) Order by c.id DESC Limit 20
This is my Laravel query:
DB::table('messages')
->join('users', function($join) use ($user_id) {
$join->select(DB::raw('CASE WHEN messages.user_one = ' . $user_id . ' THEN messages.user_two = ' . $user_id . 'WHEN messages.user_two = ' . $user_id . ' THEN messages.user_one = ' . $user_id));
$join->on(function($query) use ($user_id)
{
$query->where('messages.user_one', '=', $user_id);
$query->orWhere('messages.user_two', '=',$user_id);
});
})
->select('users.*', 'messages.*')
->get();

MULTIPLE LEFT JOINS AND ORDER BY

I have following query on in my file:
function getItems($ShowFeatured,$OrderBy,$Order,$amountShow,$ShowPropertyID)
{
switch($OrderBy) {
case 0 :
$OrderBy = 'p.id';
break;
case 1 :
$OrderBy = 'p.name';
break;
case 2 :
$OrderBy = 'p.price';
break;
case 3 :
$OrderBy = 'p.hits';
break;
case 4 :
$OrderBy = 'p.refresh_time';
break;
}
switch($Order) {
case 0 :
$Order = 'ASC';
break;
case 1 :
$Order = 'DESC';
break;
}
if($ShowPropertyID){$where= 'WHERE p.id IN ('.$ShowPropertyID.')';}else{$where= 'WHERE p.published = 1 ';}
if($ShowFeatured){$sqlFeatured= ' AND p.featured = 1';}
$db = &JFactory::getDBO();
$query = 'SELECT p.*, i.name as imagename,c.id as key1,c.name as name_category,t.id as key5,t.name as name_type,cy.id as key2,cy.name as name_country,s.id as key3,s.name as name_state,l.id as key4,l.name as name_locality,'
. ' CASE WHEN CHAR_LENGTH(p.alias) THEN CONCAT_WS(":", p.id, p.alias) ELSE p.id END as Pslug,'
. ' CASE WHEN CHAR_LENGTH(c.alias) THEN CONCAT_WS(":", c.id, c.alias) ELSE c.id END as Cslug,'
. ' CASE WHEN CHAR_LENGTH(cy.alias) THEN CONCAT_WS(":", cy.id, cy.alias) ELSE cy.id END as CYslug,'
. ' CASE WHEN CHAR_LENGTH(s.alias) THEN CONCAT_WS(":", s.id, s.alias) ELSE s.id END as Sslug,'
. ' CASE WHEN CHAR_LENGTH(l.alias) THEN CONCAT_WS(":", l.id, l.alias) ELSE l.id END as Lslug, '
. ' CASE WHEN CHAR_LENGTH(t.alias) THEN CONCAT_WS(":", t.id, t.alias) ELSE t.id END as Tslug '
. ' FROM #__properties_products AS p '
. ' LEFT JOIN #__properties_country AS cy ON cy.id = p.cyid '
. ' LEFT JOIN #__properties_state AS s ON s.id = p.sid '
. ' LEFT JOIN #__properties_locality AS l ON l.id = p.lid '
. ' LEFT JOIN #__properties_category AS c ON c.id = p.cid '
. ' LEFT JOIN #__properties_type AS t ON t.id = p.type '
. ' LEFT JOIN #__properties_images AS i ON p.id = i.parent '
. $where
. $sqlFeatured
. ' GROUP BY p.id '
. ' ORDER BY '.$OrderBy.' '.$Order
. ' LIMIT '.$amountShow;
$db->setQuery($query);
$items = $db->loadObjectList();
// $items = ($items = $db->loadObjectList())?$items:array();
//echo str_replace('#_','jos',$query);
return $items;
Part to get an image is following:
. ' LEFT JOIN #__properties_images AS i ON p.id = i.parent '
This query orders images by i.parent - image that I get I don't like. In my database I have row i.ordering - is it possible to order images by i.ordering on above query?
Thanks.
Something like this for you query I think will do what you want.
$query = 'SELECT p.*, i.name as imagename,c.id as key1,c.name as name_category,t.id as key5,t.name as name_type,cy.id as key2,cy.name as name_country,s.id as key3,s.name as name_state,l.id as key4,l.name as name_locality,'
. ' CASE WHEN CHAR_LENGTH(p.alias) THEN CONCAT_WS(":", p.id, p.alias) ELSE p.id END as Pslug,'
. ' CASE WHEN CHAR_LENGTH(c.alias) THEN CONCAT_WS(":", c.id, c.alias) ELSE c.id END as Cslug,'
. ' CASE WHEN CHAR_LENGTH(cy.alias) THEN CONCAT_WS(":", cy.id, cy.alias) ELSE cy.id END as CYslug,'
. ' CASE WHEN CHAR_LENGTH(s.alias) THEN CONCAT_WS(":", s.id, s.alias) ELSE s.id END as Sslug,'
. ' CASE WHEN CHAR_LENGTH(l.alias) THEN CONCAT_WS(":", l.id, l.alias) ELSE l.id END as Lslug, '
. ' CASE WHEN CHAR_LENGTH(t.alias) THEN CONCAT_WS(":", t.id, t.alias) ELSE t.id END as Tslug '
. ' FROM #__properties_products AS p '
. ' LEFT JOIN #__properties_country AS cy ON cy.id = p.cyid '
. ' LEFT JOIN #__properties_state AS s ON s.id = p.sid '
. ' LEFT JOIN #__properties_locality AS l ON l.id = p.lid '
. ' LEFT JOIN #__properties_category AS c ON c.id = p.cid '
. ' LEFT JOIN #__properties_type AS t ON t.id = p.type '
. ' LEFT JOIN (SELECT parent, MAX(ordering) AS MostImportant FROM #__properties_images GROUP BY parent) x ON p.id = x.parent '
. ' LEFT JOIN #__properties_images AS i ON x.parent = i.parent AND x.MostImportant = i.ordering '
. $where
. $sqlFeatured
. ' GROUP BY p.id '
. ' ORDER BY '.$OrderBy.' '.$Order
. ' LIMIT '.$amountShow;
You might want to use MIN instead of MAX depending on which way the ordering works

How to display rows from MySQL not older than a day?

I want to display news, for example from yesterday. Here's what my query looks like. Is there any magical line of code which would do that?
$query = '
SELECT a.*,
CASE WHEN CHAR_LENGTH(a.alias) THEN CONCAT_WS(":", a.id, a.alias)
ELSE a.id END as slug,
CASE WHEN CHAR_LENGTH(b.alias) THEN CONCAT_WS(":", b.id, b.alias)
ELSE b.id END as catslug,
b.title as category_title,
b.alias as categoryalias,
b.params as categoryparams,
u.name AS author
FROM #__content as a
LEFT JOIN #__categories as b ON a.catid = b.id
LEFT JOIN #__users AS u ON u.id = a.created_by
WHERE ' . $where. '
ORDER BY ' . $orderby. '
LIMIT ' . $limit;
The "magical" line of code should be in your WHERE clause.
e.g. if you date is only YYYY-MM-DD
$query .= 'WHERE b.created_date = '.$db->quote( date('Y-m-d', strtotime('-1 day')) ).'
e.g. if your date column is YYYY-MM-DD H:i:s
$query .= 'WHERE DATE_FORMAT(b.created_date,"%Y-%m-%d") = '.$db->quote( date('Y-m-d', strtotime('-1 day')) ).'