Codeigniter mysql join didn't work - mysql

I've a db that have 2 tables, and a search keyword, how can i join the tables, to do the select's in all the tables?
$this->db->select('*');
$this->db->from('tracks', 'genres');
$this->db->join('genres', 'genres.genreid = tracks.genre_id');
$this->db->or_where('tracks.title', $key);
$this->db->or_where('tracks.author', $key);
$this->db->or_where('genres.genreid', $key);
$this->db->order_by('tracks.rate', 'ASC');
$q = $this->db->get();

you have to have one table in from and the rest in the join
$this->db->from('tracks');

It also pays to use the join statement to do the job of your where clause(s). If you do join and then where it selects all of the join between the tables and then applies where, but with ANDs in the join, there's less work to be done for the db.

$this->db->select('*');
$this->db->from('tracks');
$this->db->join('genres', 'genres.genreid = tracks.genre_id');
$this->db->where('tracks.title', $key);
$this->db->or_where('tracks.author', $key);
$this->db->or_where('genres.genreid', $key);
$this->db->order_by('tracks.rate', 'ASC');
$q = $this->db->get();
This is the correct way of using it. You are using same table in FROM clause and JOIN this is problem. Another thing is that you are missing WHERE clause and only using or where.

Related

Laravel DB query builder left join with related counts

I am new in Laravel and facing an issue with the DB query builder.
I want to fetch all the records from users table and want to count related wishlists in wishlists table. Here is my query.
select `users`.*, count(wishlists.id) as wishlists_count from `users` left join `wishlists` on `users`.`id` = `wishlists`.`uid` where `users`.`status` = 1 group by `wishlists`.`id`
I want to do it with laravel query builder. Here is what I am trying.
$leads = DB::table('users')
->selectRaw('users.*', 'count(wishlists.id) as wishlists_count')
->leftJoin('wishlists', 'users.id', '=', 'wishlists.uid')
->where('users.status',1)
->groupBy('wishlists.id')
->get();
It is showing this error.
Argument 2 passed to Illuminate\Database\Query\Builder::selectRaw()
must be of the type array, string given.
Any help will be greatly appreciated.
Thanks in Advance.
This should work. From the documentation, the second argument to selectRaw() is an optional array of bindings.
However, you can achieve what you are looking for with a combination of select() and DB::raw()
$leads = DB::table('users')
->select('users.*', DB::raw('count(wishlists.id) as wishlists_count'))
->leftJoin('wishlists', 'users.id', '=', 'wishlists.uid')
->where('users.status',1)
->groupBy('wishlists.uid')
->get();
Edit: The above answer is wrong. I would consider the following alternatives instead.
Either you could achieve it with a Sub-Query with something like the following:
$wishlist = Wishlist::select(DB::raw('count(wishlists.id)'))
->whereColumn('uid', 'users.id')
->getQuery();
$users = User::select('users.*')
->selectSub($wishlist, 'wishlists_count')
->get();
Or with a much easier way (assuming you have a wishlists relationship set up)
Users::withCount('wishlists')->get();
foreach($users as $user) {
echo $user->wishlists_count;
}

Codeigniter select data from multiple tables from database | no join

So my question is:
Is it possible to select all data from different tables in one query?
Example1:
$query = $this->db->get('table1');
$query = $this->db->get('table2');
$query = $this->db->get('table3');
return $query->result();
Example2:
$this->db->select('*');
$this->db->from('table1', 'table2', 'table3');
$query = $this->db->get();
return $query->result();
I think the second exaple is possible. If not i want to ask how you would do that.
Thank you.
It can be done by putting the table names in an arrary
$query = $this->db
->select('*')
->from(['table1', 'table2'])
->get();
return $query->result();
But the number of rows in the result will be the product of the number of rows in each table, i.e. table1 has 3 rows and table2 has 19 you'll get 57 rows in the result. Are you sure that's what you want?
Joins are easy to write and highly efficient. Don't be afraid of them.

Need help on select statement to be used in laravel

select distinct clientID from Client where clientID not in (select clientID from courseDetails inner join course on coursedetails.courseID = course.courseID where coursedetails.courseID = '$courseID')
If your query is a complex one then you can use RAW query in laravel like:
$data = DB::select(DB::raw('your query'));
Reference
Note: DB::raw() is used to make arbitrary SQL commands which aren't parsed any further by the query builder. They therefore can create a vector for attack via SQL injection.
I give you a starting point:
$results = DB::table('Client')
->whereNotIn('clientID', function($query) use ($courseID) {
$query->select('clientID')
->from('courseDetails')
->join('course', 'courseDetails.courseID', '=', 'course.courseID')
->where('coursedetails.courseID', '=', $courseID);
})->get();
This should get you going. You can tweak it as you want to get your expected result.
Adding to #Mayank answer, you can run raw SQL and pass parameter like this
$result = DB::select('select distinct... where coursedetails.courseID = ? ', [$courseID]);

codeigniter FIND_IN_SET not working with join

I have a codeigniter-mysql requirement to select values from table_2 which joins table_1 and need to apply where statement in a comma separated field value. Tried as follows,
$where = $this->db->escape("FIND_IN_SET(table_1.id,table_2.places_id)<>0");
$this->db->select('table_2.*,GROUP_CONCAT(table_1.location)AS location');
$this->db->from('table_2');
$this->db->join('table_1', $where);
$this->db->where('ltable_2.packages_id', $id);
$results = $this->db->get();
return $results->result();
But the above codeigniter db object returns following mysql query and its not working :(
SELECT `table_2`.*, GROUP_CONCAT(table_1.location)AS location FROM `table_2` JOIN `table_1` ON 'FIND_IN_SET(table_1.id,table_2.places_id)<>0' WHERE `ltable_2`.`packages_id` = <id-goes-here>
It seems the quotes around 'FIND_IN_SET(table_1.id,table_2.places_id)<>0' creates the problem! All helps are appreciated to resolve the issue.
You could try $this->db->join('table_1', $where, false);. That would get rid of the quotes, and if otherwise your query is good, it should be fine.

Codeigniter - Active record Where Join column ambiguous

I have a problem with active record in codeigniter.
Here is my sql
$this->db->select('*');
$this->db->from('news as n');
$this->db->join('user as u', 'n.id_user = u.id_user');
$this->db->where('like >','10');
$this->db->limit(10);
$this->db->offset($offset);
$query = $this->db->get();
return $query->result_array();
The "news" table containing column 'like' and table "user" also containing column "like"
and the output is below:
Column 'like' in where clause is ambiguous
SELECT * FROM (`news` as n)
JOIN `user` as u ON `n`.`id_user` = `u`.`id`
WHERE `like` > '10' LIMIT 5
Then I replace
$this->db->where('like >','10');
with
$this->db->where('n.like >','10');
because i want like in news table... But it didn't work
Any solution?
You need to use alias of news table which is n so n.like
$this->db->select('*');
$this->db->from('news as n');
$this->db->join('user as u', 'n.id_user = u.id_user');
$this->db->where('n.like >','10');
$this->db->limit(10);
$this->db->offset($offset);
$query = $this->db->get();
return $query->result_array();
This will still not work as like is a reserved keyword of mysql. You need to change the column name to something else. Read more about mysql reserved keywords here
try something like this
$this->db->select('*');
$this->db->from('news as n');
$this->db->join('user as u', 'n.id_user = u.id_user');
$this->db->where('n.`like` >','10');
$this->db->limit(10);
$this->db->offset($offset);
$query = $this->db->get();
Note : change your column name to something other than reserved keyword
In case you have "like" as column name, put the column in apostrophes(`) like
$this->db->where('`like` >','10');
However is not a good practice to use any mysql reserved keywords as an identifier. Alter the column name to else and if you multiple table using the like column use table alias like.
$this->db->where('n.`like` >','10');
It will be better if you can avoid reserved keywords, so change like column name to likes for instance.
$this->db->where('n.likes >', 10);