SQL | get query from 2 table with condition - codeigniter

I have 2 tables, I want to display all user in list in my web, and show his last login details from table tbl_login_details but get the last login details for this user
1- diplay all my user from table - tbl_user
2- display LAST login for all user so the data of tbl_login_details must be ORDER then take THE LIMT
---------tbl_user-------
id user_id user_name
1 5 mohammed
2 7 ahmed
-------------tbl_login_details----------
id user_id last_activity
1 7 2016-5-2
2 7 2017-4-2
3 7 20-17-8-4
My Work is
$this->db->select('m.*,u.*');
$this->db->from('tbl_user m');
//$this->db->where("m.user_id", $id);
$this->db->join('tbl_login_details u ', 'u.user_id = m.user_id');
$where = 'm.user_id = u.user_id OR u.user_id = m.user_id OR m.user_id=" " ORDER last_activity';
$where = $this->db->order_by("last_activity", "desc");
$this->db->where($where);
// $this->db->limit('1');
$this->db->group_by('m.user_id');// add group_by
$query = $this->db->get();
return $query->result();

use max aggregation to find the last activity:
select userid, max(last_activity)
from tbl_user a inner join tbl_login_details b on a.userid=b.userid

are you try to get the last detail login from each user, If yes you can using ORDER DESC AND LIMIT 1
create query for display tbl_user first
SELECT * FROM tbl_user ORDER BY id ASC
then you can create query for get last user login
SELECT * FROM tbl_login_details WHERE user_id = 7 ORDER BY id DESC LIMIT 1
you can using modal pop up for display detail login.
or are you try display like this ?
id user_id user_name last_activity
1 5 mohammed 20-17-8-4
2 7 ahmed 20-17-8-4

help into CI max aggregation to find the last activity:
$query = $this->db->query("select userid, max(last_activity) from tbl_user a inner join tbl_login_details b on a.userid=b.userid");
foreach ($query->result() as $row)
{
echo $row->title;
echo $row->name;
echo $row->body;
}

Here is the simple SQL code to fetch that. You can do it CodeIgniter's way:
Implement this SQL into CodeIgniter.
SELECT tbl_user.user_id, tbl_user.user_name, tbl_login_details.user_id, tbl_login_details.last_activity FROM tbl_user, tbl_login_details WHERE tbl_user.user_id = tbl_login_details.user_id ORDER BY tbl_login_details.last_activity DESC

May be you are searching for Following
SELECT user_id, user_name, (SELECT last_activity FROM tbl_login_details WHERE tbl_login_details.user_id = tbl_user.user_id ORDER BY last_activity DESC LIMIT 1) as last_activity FROM tbl_user
updated code. search for how to write this sub query in active record. or just use custom query like $query = $this->db->query("YOUR QUERY");

Hope this can help you
SELECT u.id,u.user_id,u.user_name,MAX(l.last_activity) AS last_activity
FROM tbl_user u
LEFT JOIN tbl_login_details l ON(u.user_id=l.user_id)
GROUP BY u.user_id
on codeigniter custom query builder
$query = $this->db->query("SELECT u.id,u.user_id,u.user_name,MAX(l.last_activity) AS last_activity FROM tbl_user u LEFT JOIN tbl_login_details l ON(u.user_id=l.user_id) GROUP BY u.user_id");
foreach ($query->result() as $row)
{
echo $row->id;
echo $row->user_id;
echo $row->user_name;
echo $row->last_activity ;
}

Related

How to sort with COUNT laravel eloquent relations between 3 tables

I have the following function that lists the Leads and the pages, I am asked to sort it by the activities but I have the problem that this is from another table if I do it in SQL mode I get the result, but with the actual writing of the code I don't get it.
This is my query, it has join with contacts and a left join with activities, the problem is that I only need to be able to sort it by activities.
SELECT l.id,l.status_id,l.user_id,l.created_at,l.ticket_id,l.last_lead, c.full_name, COUNT(a.lead_id) as total FROM `leads` l join contacts c on l.contact_id = c.id left join activities a on a.lead_id =l.id where active=1 and status_id=7 and project_id in (8,9,10,11) GROUP by l.id order by total desc;
And this is my eloquent query:
Order by comments.
if ($sortField == 'last_comment') {
$user = User::withRole(['salesman'])->pluck('id');
$sortField = Comment::select('created_at')
->whereColumn('comments.lead_id','leads.id')
->where('comments.user_id',implode(',',$user->toArray()))
->latest()
->take(1);
}
$leads_ = $this->leads
->openedStage() // where status_id = 7
->ticketActive() // where active = 1
->searchTickets($projects)
->orderBy($sortField,'desc')
->paginate((int)$per_page);
Where the following methods mean:
**openedStage()**: where status_id = 7
**ticketActive()**: where active = 1
**searchTickets($projects):
whereHas('contacts', function ($q) use ($projects){
$q->whereIn('project_id',$projects->toArray());
});

Which is the best efficient way to get many-to-many relation count in laravel?

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.

Codeigniter automatically add field to order_by

I want to get most view by query:
$this->db->select("a.pid, a.title, a.pic, a.date_created, d.view as post_view");
$this->db->from("posts as a");
$this->db->join('views as d', 'd.post_id=a.pid');
$this->db->join('cats as b', 'b.catid=a.catid'); //ensure Cat existed
$this->db->where("a.block", 0);
$this->db->order_by("d.view", "desc");
$this->db->limit(5);
$query = $this->db->get();
return $query->result();
but always automatically add order_by pid asc. and never order desc for d.view field. i try to print query string and here:
SELECT `a`.`pid`, `a`.`title`, `a`.`pic`, `a`.`date_created`, `d`.`view` as `post_view` FROM `posts` as `a` JOIN `views` as `d` ON `d`.`post_id`=`a`.`pid` JOIN `cats` as `b` ON `b`.`catid`=`a`.`catid` WHERE `a`.`block` =0 ORDER BY `pid` asc, `d`.`view` DESC LIMIT 5
Any suggestion to fix? (CI version 3.*)

Interleaving the rows of two different SQL tables, group by one row

My Sql query is like this
$view = mysql_query ("SELECT domain,count(distinct session_id) as
views FROM `statistik` left join statistik_strippeddomains on
statistik_strippeddomains.id = statistik.strippeddomain WHERE
`angebote_id` = '".(int)$_GET['id']."' and strippeddomain!=1
group by domain having count (distinct session_id) >
".(int)($film_daten['angebote_views']/100)." order
count(distinct session_id$vladd) desc limit 25");
How can I write its Codeigniter Model I appreciate any Help
try this
$this->db->select('statistik.domain,statistik.count(DISTINCT(session_id)) as views');
$this->db->from('statistik');
$this->db->join('statistik_strippeddomains', 'statistik_strippeddomains.id = statistik.strippeddomain', 'left');
$this->db->where('angebote_id',$_GET['id']);
$this->db->where('strippeddomain !=',1);
$this->db->group_by('domain');
$this->db->having('count > '.$film_daten['angebote_views']/100, NULL, FALSE);
$this->db->order_by('count','desc');
$this->db->limit('25');
$query = $this->db->get();
Comment me If you have any query.

Querying 4 tables with inner join codeigniter

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();

Resources