I have students and subjects table in many-to-many relation (pivot table is student_subject).
Student Model
public function subjects()
{
return $this->belongsToMany(Subject::class, 'student_subject');
}
Subject Model
public function students()
{
return $this->belongsToMany(Student::class, 'student_subject');
}
Here I want the particular student subjects counts. I tried the below methods it's working fine but I want the best efficient way for this purpose.
1.
$student = Student::find($id);
$subject_count = $student->subjects()->count();
I checked the SQL query through laravel debuger it shows as below
select * from `students` where `students`.`id` = '10' limit 1
select count(*) as aggregate from `subjects` inner join `student_subject` on `subjects`.`id` = `student_subject`.`subject_id` where `student_subject`.`student_id` = 10 and `subjects`.`deleted_at` is null
$student = Student::withCount('subjects')->find($id);
$subject_count = $student->subjects_count;
I checked the SQL query through laravel debuger it shows as below
select `students`.*, (select count(*) from `subjects` inner join `student_subject` on `subjects`.`id` = `student_subject`.`subject_id` where `students`.`id` = `student_subject`.`student_id` and `subjects`.`deleted_at` is null) as `subjects_count` from `students` where `students`.`id` = '10' limit 1
$student = Student::find($id);
$subject_count = $student->loadCount('subjects')->subjects_count;
I checked the SQL query through laravel debuger it shows as below
select * from `students` where `students`.`id` = '10' limit 1
select `id`, (select count(*) from `subjects` inner join `student_subject` on `subjects`.`id` = `student_subject`.`subject_id` where `students`.`id` = `student_subject`.`student_id` and `subjects`.`deleted_at` is null) as `subjects_count` from `students` where `students`.`id` in (10)
$student = Student::find($id);
$subject_count = DB::table('student_subject')->where('student_id', $student->id)->count();
I checked the SQL query through laravel debuger it shows as below
select * from `students` where `students`.`id` = '10' limit 1
select count(*) as aggregate from `student_subject` where `student_id` = 10
According to the above ways which one is best and why? or if any different best way also there?
Doing relation()->count() is probably faster.
But if all you need is the count, withCount() should be better in terms of memory consumption.
I have sql query as below, i need to convert sql to codeigniter active record.
select * from color c
left join (select pc.* from product_color pc
LEFT join product p on pc.product_id=p.product_id
WHERE p.product_id=1)x on c.id=x.color_id
In codeigniter you can get compiled query using get_compiled_select function.
Let's create inner query first.
$inner_query = $this->db->select('pc.*')
->from('product_color pc')
->join('product p','pc.product_id = p.product_id','left')
->where('p.product_id',1)
->get_compiled_select();
Now we will use inner query to create our final query.
$final_query = $this->db->select('*')
->from('color c')
->join("($inner_query) x",'c.id=x.color_id','left')
->get_compiled_select();
echo $final_query; die;
Try this into model file. and it's always better to keep sql keywords in capital.
$query = "SELECT * FROM color c
LEFT JOIN (SELECT pc.* FROM product_color pc
LEFT JOIN product p ON pc.product_id=p.product_id
WHERE p.product_id=1)x on c.id=x.color_id"
$query = $this->db->query($query);
$data = $query->result_array();
I want to do query both result and count with group_by.
$id= 2;
$limit = 10;
$offset = ($id - 1) * $limit;
$this->db->group_by('BE.etiket_id');
$this->db->from('bulten_icerigi_etiketler as BE');
$this->db->join('etiketler as E', 'BE.etiket_id=E.id', 'left');
$this->db->join('bulten_icerigi as BI', 'BE.bulten_id=BI.id', 'left');
$count = $this->db->count_all_results('', false);
$this->db->limit($limit, $offset);
$this->db->order_by('E.adi');
$results = $this->db->get()->result();
However, I have error
Error Number: 1054
Unknown column 'tbl_`E.adi' in 'field list'
Can I use count_all_results() and result() together ?
Thank you.
You can't group by columns which you didn't selected in select.
Try to use E.adi and E.id instead of BE.etiket_id in your group by.
Your query should looks like:
SELECT
COUNT(*) as count,
tbl_E.adi,
tbl_E.id
FROM tbl_bulten_icerigi_etiketler as BE
LEFT JOIN tbl_etiketler as E ON BE.etiket_id=E.id
LEFT JOIN tbl_bulten_icerigi as BI ON BE.bulten_id=BI.id
GROUP BY tbl_E.adi, tbl_E.id // here you need to change
ORDER BY tbl_E.adi
$this->db->group_by(array("E.adi", "E.id"));
I tried to send SQL request with LEFT JOIN but it doesn't display data from table2 table.
public static function top($limit)
{
return self::findBySql("
SELECT * FROM table 1 g1
LEFT JOIN table2 s1
ON (g1.id = s1.g_id AND s1.id = (
SELECT MAX(id)
FROM table2 s2 WHERE s2.g_id = g1.id
))
LIMIT :limit",
[':limit' => $limit]
)->all();
}
It seems you are adding this function to the model and self represents the model itself.
Yii will not return results from another table and will be limited to the model only if you are calling the find on a model, instead you need to use a db query as below:
$query = new \yii\db\Query;
$query->select('*')
->from('table 1 g1')
->leftJoin('table2 s1', 's1.g_id AND s1.id = (SELECT MAX(id) FROM table2 s2 WHERE s2.g_id = g1.id')
->limit($Limit);
$command = $query->createCommand();
$resp = $command->queryAll();
The correct SQL query is
SELECT * FROM table 1 g1
LEFT JOIN table2 s1
ON g1.some_field = s1.some_field
where g1.some_field = s1.some_field are the fields that define the join.
I have working code something like...:)
with user and user_friend_list
$query = new Query;
$query ->select(['user.id AS user_id', 'user_friend_list.id'])
->from('user')
->innerJoin('user_friend_list', 'user.email = user_friend_list.email');
$command = $query->createCommand();
$data = $command->queryAll();
foreach($data as $datakey)
{
//echo $datakey['id'];
$friendfind = UserFriendList::findOne($datakey['id']);
$friendfind->is_app_using_user_id=$datakey['user_id'];
$friendfind->save();
}
i have 4 tables jobs, company, employment_type & job_category the primary key for each are job_id, com_id, type_id, job_cat_id, but (com_id, type_id, job_cat_id) are foreign key to jobs table.
my query without active record work perfectly and it is as follow
select company.com_id, company.company_name, jobs.job_id, jobs.title, jobs.opening_date, jobs.closing_date, jobs.number_of_pos, employment_type.type_id, employment_type.type, job_category.job_cat_id, job_category. category from company inner join jobs on company.com_id=jobs.com_id inner join employment_type on employment_type.type_id=jobs.type_id inner join job_category on job_category.job_cat_id=jobs.job_cat_id
but if i try to use codeiginiter active record such as
$this->db->select('company.com_id, company.company_name, jobs.job_id, jobs.title, jobs.opening_date, jobs.closing_date, jobs.number_of_pos, employment_type.type_id, employment_type.type, job_category.job_cat_id, job_category. category');
$this->db->from('company');
$this->db->join('jobs','company.com_id=jobs.com_id','inner');
$this->db->join('employment_type', 'employment_type.type_id=jobs.type_id','inner');
$this->db->join('job_category', 'job_category.job_cat_id=jobs.job_cat_id','inner');
$this->db->order_by('job_id','DESC');
$this->db->limit($limit, $offset);
$query = $this->db->get();
return $query->result_array();
i end up with the following error
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '`) INNER JOIN `jobs` ON `company`.`com_id`=`jobs`.`com_id` INNER JOIN `employmen' at line 1
SELECT `company`.`com_id`, `company`.`company_name`, `jobs`.`job_id`, `jobs`.`title`, `jobs`.`opening_date`, `jobs`.`closing_date`, `jobs`.`number_of_pos`, `employment_type`.`type_id`, `employment_type`.`type`, `job_category`.`job_cat_id`, `job_category`.` category FROM (`company`) INNER JOIN `jobs` ON `company`.`com_id`=`jobs`.`com_id` INNER JOIN `employment_type` ON `employment_type`.`type_id`=`jobs`.`type_id` INNER JOIN `job_category` ON `job_category`.`job_cat_id`=`jobs`.`job_cat_id` ORDER BY `job_id` DESC LIMIT 10
Any help would be appreciated
you have a space in job_category. category remove that and you should be golden
Format your query like this
$data = array(
'company.com_id',
'company.company_name',
'jobs.job_id',
'jobs.title',
'jobs.opening_date',
'jobs.closing_date',
'jobs.number_of_pos',
'employment_type.type_id',
'employment_type.type',
'job_category.job_cat_id',
'job_category.category'
);
$this->db->select($data);
$this->db->from('company');
$this->db->join('jobs','company.com_id=jobs.com_id','inner');
$this->db->join('employment_type', 'employment_type.type_id=jobs.type_id','inner');
$this->db->join('job_category', 'job_category.job_cat_id=jobs.job_cat_id','inner');
$this->db->order_by('job_id','DESC');
$this->db->limit($limit, $offset);
$query = $this->db->get();
return $query->result_array();