codeigniter join from 2nd table id with 3rd table id multi rows - php

I want to join multiple tables, as in my picture:
Here is my code:
$this->db->select('
pt2.turl as `p_img`,
p.title as `p_title`,
p.text as `p_text`,
p.create as `p_date`,
pt3.turl as `c_img`,
u.name as `c_name`,
c.text as `c_text`,
c.create as `c_date`
');
$this->db->from('posts as p, users as u, photos as pt2, photos as pt3');
$this->db->join('comments as c', 'p.id=c.pid AND u.id=c.uid');
$this->db->join('posts as p2', 'p2.pid=pt2.id', 'rihgt');
$this->db->join('users as u2', 'u2.photoid=pt3.id', 'right');
$this->db->order_by('c.id', 'DESC');
$this->db->limit('7');
$qry = $this->db->get();
return $qry->result();

If I understand you correctly, this is kind of what you're looking for. I haven't tried it out so it may not be exact, but you shouldn't need to make 2 table associations (pt2 and pt3) for the same table in the join. Just Include them in the select and join on the unique ID's
The "Left" is a join that is centered around you're left table so everything hangs off of that. Since you are joining the users table before the photo table, you should be able to join on its columns.
Hope this helps. Let me know if I missed something. :)
$select = array(
pt2.turl as `p_img`,
p.title as `p_title`,
p.text as `p_text`,
p.create as `p_date`,
pt2.turl as `c_img`,
u.name as `c_name`,
c.text as `c_text`,
c.create as `c_date`
);
//Set tables to variables. Just makes it easier for me
$postsTable = "posts as p"; //This will be your left table.
$userTable = "Users as u";
$commentsTable = "comments as c";
$photosTable = "photos as pt2";
$this
->db
->select($select)
->from($postsTable)
->join($userTable, "p.uid = u.id", "left")
->join($commentsTable, "p.cid = c.id", "left")
->join($photosTable, "u.photoid = pt2.id", "left")
->get();

I solved this problem myself
It would be like this:
$select= array (
//'*',
'pt.turl p_img',
'p.title p_title',
'p.text p_text',
'p.create p_date',
'pt2.turl c_img',
'c.text c_text',
'u.name c_name',
'c.create c_date'
);
$from = array (
'posts p'
);
$qry = $this
->db
->select($select)
->from($from)
->join('comments c', 'c.pid=p.id')
->join('photos pt', 'pt.id=p.pid')
->join('users u', 'u.id=c.uid')
->join('photos pt2', 'u.photoid=pt2.id')
->order_by('c.create', 'DESC')
->limit('7')
->get();
return $qry->result();

Related

codeigniter, join table properties overrides other properties

I'm working on a project using codeigniter 3 and I have a following query
$this->db->select("*");
$this->db->from("questions");
$this->db->join('users', 'users.id = questions.user_id');
$this->db->where('article_id', $articleId);
$this->db->order_by('questions.id', 'DESC');
$query = $this->db->get();
return $query->result();
// query
// SELECT * FROM `questions` JOIN `users` ON `users`.`id` = `questions`.`user_id` WHERE `article_id` = 18 ORDER BY `questions`.`id` DESC
Currently, the id property from users table overrides the questions id one. The question's id is crucial.
I worry, I will have to write a custom query, which I am not really good at.
Try to do this as follow:
$this->db->select("*, questions.id as question_id");
It's obvious that properties with the same name will be overriden. That's why you should assign to them 'unique' names in select statement.
You can specifically mention the ids with alies like -
$this->db->select("questions.id as question_id, users.id as user_id, questions.*, users.*");
$this->db->from("questions");
$this->db->join('users', 'users.id = questions.user_id');
$this->db->where('article_id', $articleId);
$this->db->order_by('questions.id', 'DESC');
$query = $this->db->get();
return $query->result();
This will give you specific columns named with question_id, user_id, questions table's all columns, users table's all columns
Or another better solution to use specific column names in select with alies if required.

sql command does not execute properly

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

Laravel join same table for 2 columns

I do currently have this code:
return Datatable::query($query = DB::table('acquisitions')
->where('acquisitions.deleted_at', '=', null)
->where('acquisitions.status', '!=', 2)
->join('contacts', 'acquisitions.contact_id', '=', 'contacts.id')
->join('user', 'acquisitions.user_id', '=', 'user.id')
->select('contacts.*', 'acquisitions.*', 'acquisitions.id as acquisitions_id', 'user.first_name as supervisor_first_name', 'user.last_name as supervisor_last_name', 'user.id as user_id'))
The data from the user table is used for 2 columns: acquisitions.supervisor_id and acquisitions.user_id. I need the first_name and the last_name for both of this tables, the above query does however currently only use the id from the acquisitions.user_id field. I also tried to use a table alias, that does also not work, I assume that I'm doing something wrong here.
So in short: I also need that the query selects the data for the user, based on the id from the acquisitions.supervisor_id and makes it available as supervisor_first_name and supervisor_last_name.
According to your next to last comment on the other answer, you need a self join per reference table. Try this:
$result = DB::select('SELECT
u.name user_first_name,
u.last_name user_last_name,
u.email user_email,
s.name supervisor_name,
s.last_name supervisor_last_name,
s.email supervisor_email
FROM acquisitions a
JOIN users u ON a.user_id = u.id
JOIN users s ON a.supervisor_id = s.id');
return $result;
Note that $result is an array of StdClass objects, not a Collection, but you can still iterate it and call the current item's values:
foreach ($result as $item) {
print($item->supervisor_first_name);
}
If you need a WHERE clause, e.g. to get a specific user's row from acquisitions, you would do that by adding a parameter to the query like so:
$result = DB::select('SELECT
u.name user_first_name,
u.last_name user_last_name,
u.email user_email,
s.name supervisor_name,
s.last_name supervisor_last_name,
s.email supervisor_email
FROM acquisitions a
JOIN users u ON a.user_id = u.id
JOIN users s ON a.supervisor_id = s.id
WHERE a.user_id = ?
', [3]);
EDIT
If you need the resultset to be a Collection, you can easily convert the array to one, using the hydrate method:
$userdata = \App\User::hydrate($result); // $userdata is now a collection of models
It should be something like;
return Datatable::query($query = DB::table('acquisitions')
->where('acquisitions.deleted_at', '=', null)
->where('acquisitions.status', '!=', 2)
->join('contacts', 'acquisitions.contact_id', '=', 'contacts.id')
->join('user', 'acquisitions.user_id', '=', 'user.id')
->select( \DB::raw(" contacts.*, acquisitions.*, acquisitions.id as acquisitions_id, user.first_name as supervisor_first_name, user.last_name as supervisor_last_name, user.id as user_id ") )
);
$devices = DB::table('devices as d')
->leftJoin('users as au', 'd.assigned_user_id', '=', 'au.id')
->leftJoin('users as cu', 'd.completed_by_user_id', '=', 'cu.id')
->select('d.id','au.name as assigned_user_name','cu.name as completed_by_user_name');
Also follow this link
https://github.com/yajra/laravel-datatables/issues/161

Query for getting values from multiple tables

I have a table video with fields videoid, genre(int-foreign key), language(int-foreign key) etc. I want to get the value of genre from genre table and language from movie_languages table.
The structure of tables are given below:
video
genre
movie_languages
How can I join these 3 tables to get the language and genre related to each videos in video table. Also when user didn't select genre/language in the form, value 0 will be inserted to the table. Will this affect the query. I am using codeingiter and I tried with the following query and is not working.
$this->db->select('video.*,movie_languages.language,genre.genre');
$this->db->join('genre', 'video.genre = genre.id');
$this->db->join('movie_languages', 'video.language = movie_languages.id');
$query = $this->db->get();
Please help me.
Thanks in advance.
It will be, you need a left join in this case
Try this
$query = $this->db
->select('v.*,ml.language,g.genre')
->from('video as v')
->join('movie_languages AS ml', 'v.language = ml.id', 'left outer')
->join('genre AS g', 'v.genre = g.id', 'left outer')
->get();
try this
$this->db->select('video.*,movie_languages.language,genre.genre')
->from('video')
->join('genre', 'video.genre = genre.id')
->join('movie_languages', 'video.language = movie_languages.id');
$query = $this->db->get();

How to INNER JOIN 3 tables using CodeIgniter

Can someone Tell me how to join 3 table with php?
Example
SELECT FROM table1, table2,table on INNERJOIN -------------------
let I have 3 table.(question table ,answer table and category table)
Here is example form my webpage.
Time remaining 30 minutes(I will get "30 minutes" form Category table)
1. Question (from question table)
2. answer (from answer table)
I don't know how to join 3 table.
it should be like that,
$this->db->select('*');
$this->db->from('table1');
$this->db->join('table2', 'table1.id = table2.id');
$this->db->join('table3', 'table1.id = table3.id');
$query = $this->db->get();
as per CodeIgniters active record framework
I believe that using CodeIgniters active record framework that you would just use two join statements one after the other.
eg:
$this->db->select('*');
$this->db->from('table1');
$this->db->join('table1', 'table1.id = table2.id');
$this->db->join('table1', 'table1.id = table3.id');
$query = $this->db->get();
Give that a try and see how it goes.
I created a function to get an array with the values ​​for the fields and to join. This goes in the model:
public function GetDataWhereExtenseJoin($table,$fields,$data) {
//pega os campos passados para o select
foreach($fields as $coll => $value){
$this->db->select($value);
}
//pega a tabela
$this->db->from($table);
//pega os campos do join
foreach($data as $coll => $value){
$this->db->join($coll, $value);
}
//obtem os valores
$query = $this->db->get();
//retorna o resultado
return $query->result();
}
This goes in the controller:
$data_field = array(
'NameProduct' => 'product.IdProduct',
'IdProduct' => 'product.NameProduct',
'NameCategory' => 'category.NameCategory',
'IdCategory' => 'category.IdCategory'
);
$data_join = array
( 'product' => 'product_category.IdProduct = product.IdProduct',
'category' => 'product_category.IdCategory = category.IdCategory',
'product' => 'product_category.IdProduct = product.IdProduct'
);
$product_category = $this->mmain->GetDataWhereExtenseJoin('product_category', $data_field, $data_join);
result:
echo '<pre>';
print_r($product_category);
die;
I think in CodeIgniter the best to use ActiveRecord as wrote above.
One more thing: you can use method chaining in AR:
$this->db->select('*')->from('table1')->join('table2','table1.id=table2.id')->...
$this->db->select('*');
$this->db->from('table1');
$this->db->join('table2', 'table1.id = table2.id','JOIN Type');
$this->db->join('table3', 'table1.id = table3.id');
$query = $this->db->get();
this will give you result from table1,table2,table3 and you can use any type of join in the third variable of $this->db->join() function such as inner,left, right etc.
For executing pure SQL statements (I Don't Know About the FRAMEWORK- CodeIGNITER!!!)
you can use SUB QUERY!
The Syntax Would be as follows
SELECT t1.id
FROM example t1 INNER JOIN
(select id from (example2 t1 join example3 t2 on t1.id = t2.id)) as t2 ON t1.id = t2.id;
Hope you Get My Point!
$this->db->select('*');
$this->db->from('table1');
$this->db->join('table2', 'table1.id = table2.id', 'inner');
$this->db->join('table3', 'table1.id = table3.id', 'inner');
$this->db->where("table1", $id );
$query = $this->db->get();
Where you can specify which id should be viewed or select in specific table. You can also select which join portion either left, right, outer, inner, left outer, and right outer on the third parameter of join method.
you can modiv your coding like this
$this->db->select('a.nik,b.nama,a.inv,c.cekin,c.cekout,a.tunai,a.nontunai,a.id');
$this->db->select('DATEDIFF (c.cekout, c.cekin) as lama');
$this->db->select('(DATEDIFF (c.cekout, c.cekin)*c.total) as tagihan');
$this->db->from('bayar as a');
$this->db->join('pelanggan as b', 'a.nik = b.nik');
$this->db->join('pesankamar_h as c', 'a.inv = c.id');
$this->db->where('a.user_id',$id);
$query = $this->db->get();
return $query->result();
i hope can be resolve your SQL
function fetch_comments($ticket_id){
$this->db->select('tbl_tickets_replies.comments,
tbl_users.username,tbl_roles.role_name');
$this->db->where('tbl_tickets_replies.ticket_id',$ticket_id);
$this->db->join('tbl_users','tbl_users.id = tbl_tickets_replies.user_id');
$this->db->join('tbl_roles','tbl_roles.role_id=tbl_tickets_replies.role_id');
return $this->db->get('tbl_tickets_replies');
}

Categories