I needed a result with Group By three columns and the SQL works perfectly without any issue. I'm facing the issue when I use it in the CodeIgniter framework; it doesn't execute the query. My Code and SQL are as follows.
Code
$this->db->select(['trk.userid AS user_id', 'scr.course AS course_id'])
->from('mdl_scorm scr')
->join('mdl_scorm_scoes_track trk', 'scr.id = trk.scormid', 'inner')
->join('mdl_course_modules mcs', 'mcs.instance = scr.id', 'inner')
->where_in('trk.value', ['completed','incomplete','passed'])
->group_by(['scr.course', 'trk.userid', 'trk.scormid'])
->order_by('trk.userid', 'DESC');
SQL
SELECT `trk`.`userid` AS user_id, `scr`.`course` AS course_id
FROM (`mdl_scorm` scr)
INNER JOIN `mdl_scorm_scoes_track` trk ON `scr`.`id` = `trk`.`scormid` INNER JOIN `mdl_course_modules` mcs ON `mcs`.`instance` = `scr`.`id`
WHERE `trk`.`value` IN ('completed', 'incomplete', 'passed')
GROUP BY `scr`.`course`, `trk`.`userid`, `trk`.`scormid`
ORDER BY `trk`.`userid` DESC LIMIT 0,100;
This works fine when the group_by has only two columns, like,
->group_by(['scr.course', 'trk.userid'])
What could be the reason?
In codeigniter group_by() works with two fields only.
$this->db->group_by()
Permits you to write the GROUP BY portion of your query:
$this->db->group_by(array("title", "date")); // Produces: GROUP BY title, date
CI 3 group_by()
Edit 01
$query=$this->db->query("
SELECT `trk`.`userid` AS user_id, `scr`.`course` AS course_id
FROM `mdl_scorm` scr
INNER JOIN `mdl_scorm_scoes_track` trk
ON `scr`.`id` = `trk`.`scormid`
INNER JOIN `mdl_course_modules` mcs
ON `mcs`.`instance` = `scr`.`id`
WHERE `trk`.`value` IN ('completed', 'incomplete', 'passed')
GROUP BY `scr`.`course`, `trk`.`userid`, `trk`.`scormid`
ORDER BY `trk`.`userid`
DESC LIMIT 0,100;");
$result = $query->result_array();
return $result;
Consider a raw query in the model.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class xyz_model extends CI_Model{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function get_this_thing($month,$year)
{ $myQuery="SELECT `trk`.`userid` AS user_id, `scr`.`course` AS course_id
FROM `mdl_scorm` scr
INNER JOIN `mdl_scorm_scoes_track` trk
ON `scr`.`id` = `trk`.`scormid`
INNER JOIN `mdl_course_modules` mcs
ON `mcs`.`instance` = `scr`.`id`
WHERE `trk`.`value` IN ('completed', 'incomplete', 'passed')
GROUP BY `scr`.`course`, `trk`.`userid`, `trk`.`scormid`
ORDER BY `trk`.`userid`
DESC LIMIT 0,100;";
$query = $this->db->query($myQuery);
$result = $query->result();
return $result;
}
}
You can also pass an array of multiple values as well:
$this->db->group_by(array("title", "date")); // Produces: GROUP BY title, date
Source link
use result array instead of the result like
return $query->result_array();
Related
I have a two tables in my database instructors and courses . I want to join them and for this reason wrote this code
$this->db->join('instructors', 'instructors.id = courses.instructor_id', 'left');
$query = $this->db->get_where('courses', array('courses_slug' => $slug));
return $query->row_array();
This code means:
SELECT * FROM `courses` LEFT JOIN `instructors` ON `instructors`.`id` = `courses`.`instructor_id` WHERE `courses_slug` = 'abituriyent-hazirligi'
But when I write this code to check:
$data['courses'] = $this->popular_courses_model->get_popular_courses($slug);
echo $data['courses']['id'];
die();
It writes the instructors id, not id of the course. Where can be the problem? Thanks in advance.
You are joining two table with columns of the same name ('id'). You need to be specific in your select for the columns and rename ('AS') if necessary.
select courses.id as course_id, instructor.id as instructor_id, ...
When using joins you should explicitly call out what columns you want returned like:
$select = "c.id, c.name, c.instructor_id, i.name instructor_name";
return $this->db->select($select)
//equivalent to "instructors as i"
->join('instructors i', 'i.id = c.instructor_id', 'left')
->where('c.courses_slug', $slug)
//equivalent to "courses as c"
->get('courses c')->row_array();
I'm having a problem joining these two databases using codeigniter, I tried it using mysql and it worked.
can someone can convert it to codeigniter
This is my code
SELECT DATE_FORMAT(FROM_UNIXTIME(ex.extime), '%Y-%m-%d') as `export_report`, u.username as `Username`, ex.qdesc as `Search_Performed`,
ex.to as `Number_of_records_exported`, ex.format as `Format`
FROM cone.users u
INNER JOIN igdata.export_status as ex
ON u.id = ex.uid
WHERE DATE_FORMAT(FROM_UNIXTIME(ex.extime), '%Y-%m-%d') = '{$dateToday}'
ORDER BY u.username ASC
I also put this in my constructor
private $cone_read;
private $ixdata;
function __construct()
{
// Call the Model constructor
parent::__construct();
$this->cone_read = $this->load->database('cone_read', TRUE);
$this->ixdata = $this->load->database('cone_us', TRUE);
}
try this:
$this->db->select("DATE_FORMAT(FROM_UNIXTIME(ex.extime), '%Y-%m-%d') as export_report, u.username as Username, ex.qdesc as Search_Performed, ex.to as Number_of_records_exported, ex.format as Format");
$this->db->from('cone.users u');
$this->db->join('igdata.export_status as ex', 'u.id = ex.uid');
$this->db->where("DATE_FORMAT(FROM_UNIXTIME(ex.extime), '%Y-%m-%d') = '$dateToday'");
$this->db->order_by("u.username", "asc");
$query = $this->db->get();
This is a search function that returns each member with their most recent year registered.
I got it working with a DB::raw() call. But can't get it working with the query builder.
Working Code:
$query = DB::table('membership as m');
$query->join(
DB::raw(
'(SELECT my.*
FROM membership_years my
INNER JOIN (
SELECT member_id,MAX(membership_year) AS max_my
FROM membership_years
GROUP BY member_id
) my2
ON my.member_id = my2.member_id
AND my.membership_year = my2.max_my
) my'
)
,'m.id','=','my.member_id');
My attempt on query builder code:
$query = DB::table('membership as m');
$query->join('membership_years as my',
function($j1){
$j1->join('membership_years as my2',
function($j2){
$j2->where('my.membership_year','=','MAX(my2.membership_year)')
->on('my.member_id','=','my2.member_id');
}
)->on('m.id','=','my.member_id');
}
);
The resulting error is:
Call to undefined method Illuminate\Database\Query\JoinClause::join()
I'm not sure if this is because the $j2 doesn't have access to the join method anymore?
Raw MySQL query:
SELECT my.membership_year,m.*
FROM membership AS m
INNER JOIN
(
SELECT my1.*
FROM membership_years my1
INNER JOIN
(
SELECT member_id,MAX(membership_year) AS max_my
FROM membership_years
GROUP BY member_id
) my2
ON my1.member_id = my2.member_id
AND my1.membership_year = my2.max_my
) my
ON m.id = my.member_id
ORDER BY m.id ASC
Way 1. You can write part of the query with builder:
$query = DB::table('membership as m')
->select('my.membership_year', 'm.*')
->join(DB::raw('(
SELECT my1.*
FROM membership_years my1
INNER JOIN (
SELECT member_id, MAX(membership_year) AS max_my
FROM membership_years
GROUP BY member_id
) my2
ON my1.member_id = my2.member_id
AND my1.membership_year = my2.max_my
) my'),
'm.id', '=', 'my.member_id')
->orderBy('m.id');
Way 2. Also you can write subqueries and use toSql() method:
$sub1 = DB::table('membership_years')
->select('member_id', DB::raw('MAX(membership_year) AS max_my'))
->groupBy('member_id');
$sub2 = DB::table('membership_years as my1')
->select('my1.*')
->join(DB::raw('(' . $sub1->toSql() . ') my2'),
function ($join) {
$join
->on('my1.member_id', '=', 'my2.member_id')
->on('my1.membership_year', '=', 'my2.max_my');
});
$query = DB::table('membership as m')
->select('my.membership_year', 'm.*')
->join(DB::raw('(' . $sub2->toSql() . ') my'), 'm.id', '=', 'my.member_id')
->orderBy('m.id');
I have a query in a repository like :
$rsm = new ResultSetMapping;
$rsm->addEntityResult('\My\ProjectBundle\Entity\News', 't');
$rsm->addFieldResult('t', 'id', 'id');
$rsm->addMetaResult('t', 'account_id', 'account_id');
$qb = $this->_em->createNativeQuery(
'SELECT t.*
FROM news as t
LEFT JOIN
LEFT JOIN
WHERE
CONDITIONS CONDITIONS
',
$rsm
);
return $qb->getResult();
I simplified the above query which is used to retrieve the news that meet specific conditions.
I need to add a count() function to this query.
I have an other ManyToOne entity-relationship between Comment and News.
How to modify the query to get the comments number a given news has ?
I'm trying to add a left join to comment and add Count() in the select but I always get errors. How could I resolve this problem ?
Raw SQL with Doctrine is easier like this :
$em = $this->getDoctrine()->getManager()->getConnection();
$query = "
SELECT t.*
FROM news as t
LEFT JOIN
LEFT JOIN
WHERE
CONDITIONS CONDITIONS
";
$stmt = $em->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();
I have a problem converting my MySQL query to codeigniter syntax.
This is my MySQL query.
Select id, name, code, status, question_count, session
from s3r_set
left join
(Select set_id, count(id) as question_count
from s3r_question group by set_id) question
on question.set_id = id
left join
(SELECT session_id as session, set_id
from s3r_session) s3rsession
on s3rsession.set_id = id
order by id
This is what I've got so far in CI:
$this->db->select('id, name, code, status, question_count, session');
$this->db->from('s3r_set');
$this->db->join('s3r_question', '(Select set_id, count(id) as question_count
from s3r_question group by set_id) question
on question.set_id = id', 'left');
$this->db->join('s3r_session', '(SELECT session_id as session, set_id
from s3r_session) s3rsession
on s3rsession.set_id = id', 'left');
$this->db->order_by('id', "desc");
$q = $this->db->get();
if($q->num_rows() > 0)
{
return $q->result();
}
else
{
return false;
}
Thanks for help in advance.
Well for one you are doing the join wrong:
$this->db->join('s3r_question', '(Select set_id, count(id) as question_count
from s3r_question group by set_id) question
on question.set_id = id', 'left');
Should be:
$this->db->join('(Select set_id, count(id) as question_count
from s3r_question group by set_id) question', 'question.set_id = id');
Refer to formatting here:
http://ellislab.com/codeigniter/user-guide/database/active_record.html#join
The ...join(FROM_TABLE, ON WHAT VALUE TO JOIN ON, OPTIONAL > WHAT TYPE OF JOIN, LEFT/RIGHT/ETC;)