Laravel Query builder query equivalent to SQL query? - mysql

My query is working fine only problem in this where clause. Please tell me what will query builder query in Laravel, equivalent to this query
WHERE (interest_request.sender_id = 6 or interest_request.to_user_id = 6)
AND interest_request.interest_status =2
and profiles.profile_id not in (6)
I am using following query builder but not working
where('to_user_id',$my_profile_id)->orwhere
('sender_id',$my_profile_id)->where('interest_status','2')
->whereNotIn('profiles.profile_id', $my_profile_id)

In your particular case, you'll have to use a nested where clause:
->where(function ($query) use ($my_profile_id) {
$query->where('to_user_id', $my_profile_id)
->orWhere('sender_id', $my_profile_id);
})
->where('interest_status', 2)
->where('profile_id', '!=', $my_profile_id)
Also you don't need to use a whereIn (or whereNotIn) query if you have only one id in the list.

i would assume it will be the following in sql:
WHERE to_user_id = $my_profile_id
OR sender_id = $my_profile_id
AND interest_status = 2
AND profiles.profile_id NOT IN ($my_profile_id)
When i use orwhere() statements i use callback functions:
where(function($query) {$query->something})
->orwhere(function($query) {$query->otherOptions})

Related

Laravel QueryBuilder - Different result with `where()` and `whereRaw()` for the identical Query

I'm working on a laravel application Where I have two very similar QueryBuilder but producing different result in both conditions.
Query 1:
$ids = $this->model->leftJoin('feed', 'agents.identifier', '=', 'feed.identifier')
->whereRaw('feed.active <> agents.feed_status')
->pluck('id');
dd(count($ids)); // print 485236
Query 2:
$ids = $this->model->leftJoin('feed', 'agents.identifier', '=', 'feed.identifier')
->where('feed.active', '<>', 'agents.feed_status')
->pluck('id');
dd(count($ids)); // print 4259
I would like to know the key difference between these two QueryBuilder. Why is it producing different results, although it seems identical?
And which query returns the correct result? if I would like to find the records from agents where feed_status is not equel to feed.active.
it seem I have got the clarification. Howevere I would like to share my R&D here. Incase if anyone else got the same problem.
I have printed the raw query and get where() seems consider the third parameter as string compare instead of field compare. That's why seems the result is different.
However when we run the query with whereRaw() it's treated this as table field comparision.
Laravel Code:
$ids = $this->model->leftJoin('feed', 'agents.identifier', '=', 'feed.identifier')
->whereRaw('feed.active <> agents.feed_status')
->pluck('id');
MySql Query:
"select * from `agents` left join `feed` on `agents`.`identifier` = `feed`.`identifier` where feed.active <> agents.feed_status"
# where feed.active <> agents.feed_status
Laravel Code:
$ids = $this->model->leftJoin('feed', 'agents.identifier', '=', 'feed.identifier')
->where('feed.active', '<>', 'agents.feed_status')
->pluck('id');
MySql Query:
"select * from `agents` left join `feed` on `agents`.`identifier` = `feed`.`identifier` where `feed`.`active` <> 'agents.feed_status'"
# where feed.active <> 'agents.feed_status'
Yes, the results were meant to be different.
As where method compares a column with a literal value
->where('table.column', 'cond', 'value')
If you are looking to make comparisons in two columns without using whereRaw method; you should instead use whereColumn method
->whereColumn('table1.column1', 'cond', 'table2.column2')

How do I build a sum() query in Laravel with the add and subtract operators?

so I have a query as such;
select sum(points_add) as total_add, sum(points_subtract) as total_deducts, (sum(points_add)-sum(points_subtract)) as total_balance from tbl_points where user_id = 2;
How do I build it in Laravel? I know how to do it up until the (sum(points_add)-sum(points_subtract)) as total_balance part as I'm not sure how to query out the "-" subtract function.
For this the easiest thing would be to use selectRaw():
$values = DB::table('tbl_points')
->selectRaw('sum(points_add) as total_add, sum(points_subtract) as total_deducts, (sum(points_add)-sum(points_subtract)) as total_balance')
->where('user_id', 2)
->first();
Laravel does come with aggregates(), however, these are used to return single values instead of multiple aggregates.

laravel where clause value and column name

How can i do these in laravel query where clause?
select * from table_samples where 1 = id
// basically i can do like where id = 1
select * from table_samples where 1000 > rate
// basically i can do like where rate < 1000
select * from table_samples where 'bogart' = name
// basically i can do like where name = "bogart"
My point is if you interchange the column and value its working on mysql, but if i do this in laravel where clause it doesn't work?
Something like
TableSample::where('1','id')->first();
TableSample::where('1000','>','rate')->first();
TableSample::where('bogart','name')->first();
// throws an error undefined column name 1, 100, and bogart.
// I know laravel . These are the correct query
TableSample::where('id','1')->first();
TableSample::where('rate','<','1000')->first();
TableSample::where('name','bogart')->first();
Is there any where clauses functions in laravel that can accept or determine if you try to interchange the value and column?
You yan use DB::raw() for this.
TableSample::whereRaw('? = id', [1])->first();
Just make sure you use parameter substitution like above to prevent creating sql injection vulnerabilities.
https://laravel.com/docs/5.6/queries#raw-expressions
The whereRaw and orWhereRaw methods can be used to inject a raw where clause into your query
TableSample::whereRaw('1 = id')->first();
https://laravel.com/docs/5.6/queries#raw-methods

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

How to turn this SQL into a Laravel Query Builder query?

I have the following query in SQL that works perfectly but I can't get it to work in Laravel's query builder. Here is the SQL:
SQL
select count(listings_queue.mls_listing_id) from listings_queue
INNER JOIN listings
ON `listings_queue`.`mls_listing_id` = `listings`.`mls_listing_id`
WHERE `listings`.`mls_id`=`listings_queue`.`mls_id`
AND `listings`.`city`=`listings_queue`.`city`
Laravel Query Builder
$count = DB::table('listings_queue')
->join('listings', function($join)
{
$join->on('listings_queue.mls_listing_id', '=', 'listings.mls_listing_id');
})
->where('listings.mls_id','=','listings_queue.mls_id')
->where('listings.city', '=', 'listings_queue.city')
->count();
This produces a count of 0 yet the SQL above produces 11,550 rows.
If I do the Laravel Query Builder and use the toSql(); at the end, I get:
toSql(); in Laravel
select * from `listings_queue`
inner join `listings`
on `listings_queue`.`mls_listing_id` = `listings`.`mls_listing_id`
where `listings`.`mls_id` = ?
and `listings`.`city` = ?
The crazy thing here is that the raw SQL output looks the same other than the ? bindings. Coudl that be the problem? I don't understand why my query builder query running on the same database as the raw SQL at the top produces different results.
One other clue is that if I remove the where clause in my laravel query builder query, I get results.
I asked this question elsewhere but didn't do a good job explaining so here it is. Thanks so much for any help you can provide!
Remove the Closure like:
$count = DB::table('listings_queue')
->join('listings', 'listings_queue.mls_listing_id', '=', 'listings.mls_listing_id')
->where('listings.mls_id','=','listings_queue.mls_id')
->where('listings.city', '=', 'listings_queue.city')
->count();
Try this multiple condition of join
$count = \DB::table('listings_queue')
->select('listings_queue.*')
->distinct()
->join('listings', function ($join)
{
$join->on('listings_queue.mls_listing_id', '=', 'listings.mls_listing_id')
->on('listings_queue.mls_id', '=', 'listings.mls_id')
->on('listings_queue.city', '=', 'listings.city');
})
->count();