I have this strange situation and not sure of what is wrong. I have a simple self join to find matches based on some conditions. I have this query running fine in mysql but when I call it through PHP, it doesn't return any values.
select * from Requests p inner join Requests c on c.ID<>p.ID
where usr_ID<>4
and p.c_ID = c.c_ID
This works fine but not the below one.
DB::table('Requests as parent')
->join('Requests as child', 'parent.ID', '<>', 'child.ID')
->where('parent.usr_ID', '<>', 4)
**->where('parent.c_ID', '=', 'child.c_ID')**
->get();
In the above query, if I remove the second where condition(c_ID), it returns correct values. For all rows, this has a value of 1. If I replace child.c_ID or parent.c_ID by 1, it works again. I have tried with other columns as well and found the same issue.
Any pointers?
What the query builder makes out of your second where condition is:
WHERE parent.c_ID = 'child.c_ID'
So instead of a "normal" where() use whereRaw(), which takes your input and injects it right into the final SQL query
->whereRaw('parent.c_ID = child.c_ID')
Alternatively you could also use DB::raw() on the third argument
->where('parent.c_ID', '=', DB::raw('child.c_ID'))
Both are essentially the same so use whichever you like more.
Related
I have the following query which I'm trying to convert into Laravel's query builder so I can take advantage of automatic escaping etc.
SELECT subjects.name, report_comments.comment
FROM subjects
LEFT JOIN (report_comments, library_comments) ON subjects.id = library_comments.subject_id
AND report_comments.library_comment_id = library_comments.id
AND report_comments.report_id = 1
Effectively what the query says is 'get the names of all the subjects, and if they have a matching report_comment (via the intermediate library_comments table), return that along with the subject' (a subject has either one or zero report_comments for the given criteria). The query works if I run it directly in MySQL and returns the results I'd expect. The report_comment.report_id = 1 is hard-coded at the moment but will eventually be a placeholder so that any report_id can be passed in.
So far I've managed to get:
DB::table('subjects')->select(['subjects.name', 'report_comments.comment'])->leftJoin('report_comments', function ($join) {
$join->on('subjects.id', '=', 'library_comments.subject_id')
->on('report_comments.library_comment_id', '=', 'library_comments.id')
->on('report_comments.report_id', '=', '1');
})
If I add toSql the result is:
select `subjects`.`name`, `report_comments`.`comment` from `subjects` left join `report_comments` on `subjects`.`id` = `library_comments`.`subject_id` and `report_comments`.`library_comment_id` = `library_comments`.`id` and `report_comments`.`report_id` = `1`
This is almost what I want, except it fails because the library_comments table is not mentioned at all:
Illuminate/Database/QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'library_comments.subject_id' in 'on clause' (SQL: select `subjects`.`name`, `report_comments`.`comment` from `subjects` left join `report_comments` on `subjects`.`id` = `library_comments`.`subject_id` and `report_comments`.`library_comment_id` = `library_comments`.`id` and `report_comments`.`report_id` = `1`)'
What I need to do is tell the leftJoin function about report_comments and library_comments, but there doesn't seem to be any way to do this. I tried:
leftJoin(['report_comments', 'library_comments'], function($join)
on a guess that Laravel might convert an array of table names into (report_comments, library_comments), but that didn't work and gave me the following warning:
PHP Notice: Array to string conversion in /home/paul/sites/report-assistant/vendor/laravel/framework/src/Illuminate/Database/Grammar.php on line 39
Is there a way to pass multiple tables into leftJoin, or do I need to completely rewrite the query in order to work with Laravel's query builder?
I'm using laravel/framework version 5.8.21 and all my dependencies are up to date (composer update && npm update).
Use BD::raw
write query like this and It will work
DB::table('subjects')->select(['subjects.name, report_comments.comment'])->leftJoin(DB::raw('(report_comments, library_comments)'), function ($join) {
$join->on('subjects.id', '=', 'library_comments.subject_id')
->on('report_comments.library_comment_id', '=', 'library_comments.id')
->on('report_comments.report_id', '=', '1');
})
Not sure if this will work but i assume it will be somthing along these lines, hopefully you get something out of it.
Basically added a check to see if the relationship exists if it does then join it.
Subject::select('subjects.name, report_comments.comment')
->leftJoin('library_comments', 'subjects.id, '=', library_comments.subject_id')
->leftJoin('report_comments', function($join){
if(report->library->relationship){
$join->on('report_comments.library_comment_id', '=', 'library_comments.id')
->where('report_comments.report_id', '=', '1');
}
})
After a bit of tinkering, I managed to find the answer in two parts:
First, I had to tweak this part of the join:
on('report_comments.report_id', '=', '1')
and replace it with:
where('report_comments.report_id', '=', '1')
If I didn't do this, Laravel would quote 1 with backticks, causing MySQL to interpret it as a column name.
The other change was to use DB::raw, which I was trying to avoid but I don't think it's too bad in this situation because I'm passing a hardcoded string rather than user input (or anything influenced by user input). The leftJoin now looks like:
leftJoin(DB::raw('(report_comments, library_comments)')
For a search query I have the following:
DB::whereRaw('column = ?', 'foo')->orWhereRaw('column IS NULL')->get();
Adding the orWhereRaw statement gives me less results than only the whereRaw. Somehow it seems to ignore the first when adding the other. It is included in the SQL statement. Is there another way to compare for a string and null value?
I have also tried the following, as suggested below:
return self::select('id')
->where('current_state', 'unavailable')
->orWhereNull('current_state')
->get();
If I change the order (the whereNull first and the where second) this also gives me different results. It appears as if the inclusive query doesn't function correctly in correspondence with the where clause. If I use to regular where clauses I don't experience any issues.
Running SELECT * FROM events WHERE current_state='unavailable' OR current_state IS NULL; does produce the correct result for me.
Don't use whereRaw to check for null. You can use this instead:
->orWhereNull('column')
The proper way to do the first where, unless you're doing something extra such as a mysql function, is just to pass the column along like this:
where('column', '=', 'foo')
You can actually eliminate the equals, since it defaults to that. So your query would be:
DB::table('table')->where('column', 'foo')->orWhereNull('column')->get();
I got this query written out in Laravel query builder, bu when i run it, it returns this error: Call to a member function join() on float
$avgYield= DairyCropYield::avg('moisture')
->join('dairy_crops','dairy_crops.id','=','dairy_crop_yields.dairy_crop_id')
->join('dairy_crop_varieties','dairy_crops.dairy_crop_variety_id','=','dairy_crop_varieties.id')
->where('dairy_crop_varieties.crop','=',$crop->crop)
->whereYear('harvested_at','=',Carbon::now()->year)
->get();
But when i write the same query in mySql it wroks as exptected:
SELECT AVG(moisture) FROM dairy_crop_yields AS yield JOIN dairy_crops AS crop ON crop.id = yield.dairy_crop_id JOIN dairy_crop_varieties AS variety ON variety.id = crop.dairy_crop_variety_id WHERE variety.crop = 'corn' AND YEAR(harvested_at) = 2015
Any thoughts / suggestions on what I am not doing right in Laravel query builder.
I do want to master and stick with Laravel's query builder.
Thanks.
Put the avg after the get(), the avg method works on a collection. So what you want is to get() all the result first then only call the avg('moisture') on the available results.
$avgYield= DairyCropYield::join('dairy_crops','dairy_crops.id','=','dairy_crop_yields.dairy_crop_id')
->join('dairy_crop_varieties','dairy_crops.dairy_crop_variety_id','=','dairy_crop_varieties.id')
->where('dairy_crop_varieties.crop','=',$crop->crop)
->whereYear('harvested_at','=',Carbon::now()->year)
->get()
->avg('moisture');
Alternately, you can also do something like this using DB::raw
$avgYield= DairyCropYield::select(DB::raw('AVG(moisture)'))
->join('dairy_crops','dairy_crops.id','=','dairy_crop_yields.dairy_crop_id')
->join('dairy_crop_varieties','dairy_crops.dairy_crop_variety_id','=','dairy_crop_varieties.id')
->where('dairy_crop_varieties.crop','=',$crop->crop)
->whereYear('harvested_at','=',Carbon::now()->year)
->get();
Here is my join query for getting data from two tables.
$this->db->select('*');
$this->db->from('george_hotel_bkd_customers');
$this->db->where('george_hotel_bookings.bookingref',$ref);
$this->db->join('george_hotel_bookings', 'george_hotel_bookings.user_id = george_hotel_bkd_customers.user_id');
$query = $this->db->get();
According to my where condition it returns only one row but it will returns all the rows with matches the join condition.
Seems like my where condition is not executed here.
please help me
What does $ref =, how many results should it pick up roughly?
what do you get when you omit the where? if you get full result then must be an issue with $ref value, or, that is the result.
Just a note, you don't need to select(*), this is default, if this is an just for examples sake, sorry for picking up. You can also add the ->from(whaterver_table) to ->get(whatever_table) You need to add ->get() anyway, so why not remove the ->from() line, just a choice of readability, but i did not realise you could do this for a while, so thought id add it to my answer.
Or another problem solving path is whether the join should be 'left' as 3rd arg. IE is there always a join?
Altering the position or the join in the statement would not make any difference, as Anant suggested
$this->db->select('*');
$this->db->from('george_hotel_bkd_customers');
$this->db->join('george_hotel_bookings', 'george_hotel_bookings.user_id = george_hotel_bkd_customers.user_id');
$this->db->where('george_hotel_bookings.bookingref',$ref);
$query = $this->db->get();
always where is last
I am newbie on Laravel, I have a proper SQL Statement (which works on PHPMyAdmin and Navicat) and I can get results. What i want to do is, I want to take that statements in Laravel without using DB::raw();.
Any Helps will be appreciated.
Select
rmm.message,
count(rmm.message) as number,
receivedTime as time
FROM
rcs rcs, rmm rmm
WHERE
rmm.smsCid = rcs.smsCid AND rmm.receivedTime LIKE '%2013-04-01%' AND length('rmm.message') > '3'
GROUP BY(rmm.message)
Alternatively you can use the Fluent Query Builder. Here's my attempt, of course it's not checked as I don't have your data structure to hand. Hopefully enough to get you started:
DB::table('rcs') // SELECT FROM rcs
->join('rmm', 'rmm.smsCid', '=', 'rcs.smsCid') // Simple INNER join
->where('rmm.receivedTime', 'LIKE', '%2013-04-01%')
->where(DB::raw('LENGTH(rmm.message)'), '>', 3)
->get(array(DB::raw('COUNT(rmm.message)'), 'rmm.message', 'receivedTime')); // Get only the columns you want
You can use DB::query() to run your query. This calls the query method on the active DB connection.