Convert this MySQL Query to Codeigniter Active Record - php

I have got two tables :
Dress (dress_id, title)
Dress_comment (comment_id, dress_id, comment)
I have been trying from hours now and unable to convert this query into the corresponding Codeigniters' Active Class Record functions.
Here is the query :
SELECT d.dress_id, d.title, COALESCE(dc.count, 0)
FROM dress d
JOIN (select dress_id, count(comment_id) as count from dress_comment group by dress_id) dc
ON d.dress_id = dc.dress_id
ORDER BY d.dress_id;
This is what I have tried till now :
//Creating the select subquery for the inner join
$this->db->select('dress_id, count(comment_id) as count')
->from('Dress_comment')
->group_by('dress_id')
->get();
$subQuery = $this->db->last_query();
//Main Query
$this->db->select('d.dress_id, d.title, COALESCE(dc.count,0)')
->from('Dress')
->join($subQuery . ' dc','dc.dress_id = d.dress_id','left')
->order_by('d.dress_id');
$result = $this->db->get();
return $result->result_array();
But Codeigniter is not running this query and always giving mysql syntax error. The sql format that codeigniter is converting this active methods to is
SELECT `d`.`dress_id`, `d`.`title`, COALESCE(dc.count, `0)`
FROM (`Dress`) LEFT JOIN `SELECT` `dress_id`, count(comment_id) as count
FROM (`Dress_comment`)
GROUP BY `dress_id` dc
ON `dc`.`dress_id` = `d`.`dress_id`
ORDER BY `d`.`dress_id`

I was able to solve the problem using the mysql query in the join function like this :
$this->db->select('d.dress_id, d.title, dc.count as comments, dl.count as likes, dt.title, di.image_url')
->from('Dress d')
->join('(select dress_id, count(comment_id) as count from dress_comment group by dress_id) dc','dc.dress_id = d.dress_id','left')
->order_by('d.dress_id');

Related

inner join with union in codeigniter

i m applying union on single table and i want apply inner join with union in codeigniter on it. how can i do that i have tryed many ways but everytime i got syntax error
this is my code:-
$this->db->select(' COUNT(marks.old_id) AS count, MIN(marks.mark) AS min , MAX(marks.mark) AS max ')
->from('marks')
->where('type', 'hard')
->group_by('marks.id');
$this->db->get();
$query1 = $this->db->last_query();
$this->db->select(' COUNT(marks.old_id) AS count, MIN(marks.mark) AS min , MAX(marks.mark) AS max ')
->from('marks')
->where('type', 'easy')
->group_by('marks.id');
$this->db->get();
$query2 = $this->db->last_query();
$query = $this->db->query($query1 . ' UNION ' . $query2);
// $this->db->select('newuser.*')
// ->from('newuser')
// ->join('marks', 'newuser.id = marks.old_id', 'left')
// ->group_by('newuser.id')
// ->order_by('newuser.id', 'ace');
return $query->result();
please help me...
CodeIgniter's active records don't support UNION, so you would just write your query and use the active records query method. , Please check this post Union query with codeigniter
Codeigniter active record not supporting a union Write a raw query for union...

How to retrieve record in group by with join table depend on MAX?

This my query in model:
return $this->db->join('tbl_customer', 'tbl_customer.cus_code = tbl_cus_account.custcode')
->where("status", 1)
->where("DATE_FORMAT(nextbillingdate,'%Y-%m') <= ", date('Y-m'))
->select('*,MAX(issuewithmain) AS issuewithmain, SUM(monthlyfee) AS monthlyfee, count(accountcode) as rows')
->group_by('custcode')
->get('tbl_cus_account');
The below are my table for join query:
-The result I want as the image below:
Your query can be something like this
SELECT t.*, t2.rows, t2.monthlyfee from tbl_cus_account t join (SELECT MAX(issuewithmain) AS issuewithmain, custcode, count(accountcode) as rows, SUM(monthlyfee) AS monthlyfee from tbl_cus_account JOIN tbl_customer ON tbl_customer.cus_code = tbl_cus_account.custcode where status = 1 AND DATE_FORMAT(nextbillingdate,"%Y-%m") <= DATE_FORMAT(now(),"%Y-%m") GROUP BY custcode) t2 on t.issuewithmain = t2.issuewithmain and t.custcode = t2.custcode
Here you made an extra join to the same table, to only get the exactly records that match with your max(issuewithmain)
You need to transform this query to codeigniter and add the conditions of the where to the corresponding table.
Maybe something like this, I haven't test it
UPDATE
return $this->db->join('(SELECT MAX(issuewithmain) AS issuewithmain, custcode, count(accountcode) as rows, SUM(monthlyfee) AS monthlyfee from tbl_cus_account where status = 1 AND DATE_FORMAT(nextbillingdate,"%Y-%m") <= "'.date('Y-m').'" GROUP BY custcode) t2', 'tbl_cus_account.issuewithmain = t2.issuewithmain AND t2.custcode = tbl_cus_account.custcode')->select('tbl_cus_account.*, t2.monthlyfee, t2.rows') ->join('tbl_customer', 'tbl_customer.cus_code = t2.custcode') ->group_by('t2.custcode') ->get('tbl_cus_account');

Converting SQL query to codeigniter active record

I am working on a private message app using CodeIgniter.
I have 3 tables:
conversations
conversations_messages
conversations_members.
I am trying to join the tables by matching the conversations ids and fetch all the messages for the user who's logged in.
This is the standard sql query
SELECT
'conversations','conversation_id',
'conversations','conversation_subject',
MAX('conversations_messages','message_date') AS 'conversation_last_reply'
FROM 'conversations'
LEFT JOIN 'conversations_messages' ON 'conversations'.'conversation_id' = 'conversations_messages'.'conversation_id'
INNER JOIN 'conversations_members' ON 'conversations'.'conversation_id' = 'conversations_members'.'conversation_id'
WHERE 'conversations_members', 'user_id' = $sender_id
AND 'conversations_members','conversation_deleted' = 0
GROUP BY 'conversations'.'conversation_id'
ORDER BY 'conversation_last_reply' DESC";
Its a big query, hence; I'm not sure how to convert it to CodeIgniter active records or simply make it run with the framework.
Any corrections would be appreciated too.
Try below code with CodeIgniter active record.
$this->db->select('conversations, conversation_id, conversation_subject');
$this->db->select_max('conversations_messages.message_date', 'conversation_last_reply');
$this->db->from('conversations');
// Joining with conversations_messages table
$this->db->join('conversations_messages','conversations.id=conversations_messages.conversation_id','left');
$this->db->join('conversations_members','conversations.id= conversations_members.conversation_id','inner');
$this->db->where('conversations_members.user_id',$sender_id);
$this->db->where('conversations_members.conversation_deleted','0');
$this->db->group_by('conversations.conversation_id');
$this->db->order_by('conversation_last_reply');
// Get the results from db
$query = $this->db->get();
// Result array contains the records selected
$result_array = $query->result_array();
Happy coding
Naseem
$this->db->select('conversations, conversation_id, conversation_subject');
$this->db->select_max('conversations_messages.message_date', 'conversation_last_reply');
$this->db->from('conversations');
// Joining with conversations_messages table
$this->db->join('conversations_messages','conversations.id=conversations_messages.conversation_id','left');
$this->db->join('conversations_members','conversations.id= conversations_members.conversation_id','inner');
$this->db->where('conversations_members.user_id',$sender_id);
$this->db->where('conversations_members.conversation_deleted','0');
$this->db->group_by('conversations.conversation_id');
$this->db->order_by('conversation_last_reply');
// Get the results from db
$query = $this->db->get();
// Result array contains the records selected
$result_array = $query->result_array();

getting three records in descending order of each category using codeigniter

I've two categories and I want to fetch three records of each category later I found this link UNION query with codeigniter's active record pattern after this I change my DB_Active_rec file and add this code also
var $unions = array();
public function union_push($table = '') {
if ($table != '') {
$this->_track_aliases($table);
$this->from($table);
}
$sql = $this->_compile_select();
array_push($this->unions, $sql);
$this->_reset_select();
}
public function union_flush() {
$this->unions = array();
}
public function union() {
$sql = '(' . implode(') union (', $this->unions) . ')';
$result = $this->query($sql);
$this->union_flush();
return $result;
}
public function union_all() {
$sql = '(' . implode(') union all (', $this->unions) . ')';
$result = $this->query($sql);
$this->union_flush();
return $result;
}
and then I create codeigniter's function based query like this
$this->db->select("*");
$this->db->from("media m");
$this->db->join("category c", "m.category_id=c.id", "INNER");
$this->db->order_by("m.media_files", "DESC");
$this->db->limit(3);
$this->db->union_push();
$this->db->select("*");
$this->db->from("media m");
$this->db->join("category c", "m.category_id=c.id", "INNER");
$this->db->order_by("m.media_files", "DESC");
$this->db->limit(3);
$this->db->union_push();
$getMedia = $this->db->union_all();
create this
(SELECT * FROM media m INNER JOIN category c ON
m.category_id = c.id ORDER BY m.media_files DESC LIMIT 3)
UNION ALL
(SELECT * FROM media m INNER JOIN category c ON
m.category_id = c.id ORDER BY m.media_files DESC LIMIT 3)
Now it is fetching records but not properly I want to use only query, it showing six records first query fetch 3 records and second query fetch three records now records are duplicate I check the id of records it is 6,5,4 and again 6,5,4. It can be done also by PHP but I want to use query. Thanks in advance
I dont know code-igniter, but basicly you want it to do the union first and then apply the order by over the whole set. This would require a subquery. It should result in the following SQL query:
select * from
((SELECT * FROM media m INNER JOIN category c ON m.category_id = c.id )
UNION ALL
(SELECT * FROM media m INNER JOIN category c ON m.category_id = c.id)) T
ORDER BY m.media_files DESC LIMIT 3
Hope it helps you some.

Order by a SUM with multiple joins in codeigniter

Solution:
$query = $this->db->query("
SELECT *, SUM(views.times) AS sum
FROM channel
RIGHT JOIN video
ON channel.channel_id = video.channel_id
LEFT JOIN user
ON channel.user_id = user.user_id
LEFT JOIN views
ON channel.channel_id = views.channel_id
GROUP BY channel.channel_name
ORDER BY sum DESC
");
I have a query that returns a list of items.
function getfrontpage(){
$this->db->select('*');
$this->db->from('channel');
$this->db->join('video', 'channel.channel_id = video.channel_id' , 'right');
$this->db->join('user', 'channel.user_id = user.user_id');
$this->db->group_by("channel.channel_name");
$query = $this->db->get();
return $query->result();
}
Now i'm trying to order these with the SUM from another table, how can i achieve this?
Here is a picture from that table:
I want the results to be sorted by the SUM of the total of "times" for each "channel_id"
thanks in advance
I would suggest to run this through $this->db->query() instead.
It's nice to fetch simple values through CodeIgniters AR functions. But at some situations it's simply easier to build query strings instead.
In your case:
$query = $this->db->query("
SELECT channel_id, SUM(times) AS sum
FROM channel
GROUP BY channel_id
ORDER BY sum DESC
");
You can also escape most values through db->query()!
$this->db->query("
SELECT name
FROM table_name
WHERE id = ?
", array(1));
Isn't it as simple as $this->db->order_by("channel_id", "desc");? this orders the results by channel_id in descending order.
Assuming the table displayed in your question is called times_table, and has a key of user_id, channel_id, you can use the following code to join the times_table into your query so the "times" column is available to sort by.
$this->db->join("times_table", "times.user_id=channel.user_id, times.channel_id=channel.channel_id", "left");
// You've already grouped by channel_name, so grouping by channel_id is probably not necessary.
$this->db->order_by("SUM(times_table.times) DESC");
N.B. I just guessed the name of your displayed table is times_table.

Categories