Subquery Where condition on Laravel query builder - php

my problem is simple, I'm a student, I'm learning laravel, i don't know how to create a where condition from a subquery.
This is the query
"SELECT id_parameter,value,code_rule,block,grouping,count FROM rule_definition WHERE (code_rule IN (SELECT code_rule FROM rule_definition WHERE id_parameter = 1 AND value = '$x') AND (id_parameter = 1 AND value = '$x')) OR (id_parameter != 1 AND value != '$x')";
Im using laravel 6.0 query builder.
Thanks

I don't think you need that subquery. Because it from the same table and same condition.
$query = DB::table('rule_definition')
->select('id_parameter, value, code_rule, block,grouping, count')
->where(function ($q) use ($x) {
$q->where('id_parameter','=',1)
->where('value','=',$x);
})->orWhere(function ($q) use ($x) {
$q->where('id_parameter','!=',1)
->where('value','!=',$x);
})

$query = DB::table('rule_definition')->where(function ($q){
$q->where('id_parameter','=',1)
->where('value','=','$x');
})->orWhere(function ($q){
$q->where('id_parameter','!=',1)
->where('value','!=','$x');
})->select('id_parameter, value, code_rule, block,grouping, count')

Related

Laravel and PHP - Condition in the SQL request

I have a query
$BaseUsers = DB::table('users', 'users.ustatus', '=', '1')
->join('user_infos', 'user_infos.user_id', '=', 'users.id')
->select('users.*', 'user_infos.add1', 'user_infos.add3')
->paginate(3);
It work fine. But i need insert condition "where" to search in result
i send $request from form. How insert condition to query?
In PHP it looks like this:
if($request['add_1'])
{
$insert1=" and add_1<>'' ";
}
if($request['add_2'])
{
$insert2=" and add_2<>'' ";
}
...
$sql=" SELECT users.*, user_infos.add1, user_infos.add3 FROM users JOIN user_infos where users.ustatus=1 and user_infos.user_id=users.id ".$insert1." ".$insert2."";
How can this be done on laravel in Controller? I mean - just insert the necessary condition insert1, insert2 ... into the query
you can use where() and has() to build your query
$query = DB::table('users');
if($request->has('age')) {
$query->where('age', '>', $request->age);
}
$query = $query->get();
I hope it's helpful
All is simple ) I use when in query
$BaseUsers = DB::table('users', 'users.ustatus', '=', '1')
->join('user_infos', 'user_infos.user_id', '=', 'users.id')
->when($request->input('f_add3'), function ($query) {
return $query->where('user_infos.add3', '<>', '');
})
->select('users.*', 'user_infos.add1', 'user_infos.add3')
->paginate(3);

using WHERE condition1 AND condition2 in ::selectraw

I am using ::selectRaw inside my PHP function and I need that statement to get two conditions. In my case, I am using my category_id column
I tried to do two where but seems like these conflict with each other:
$query = self::selectRaw((is_array($fields)?implode(", ",$fields):$fields))
->where('category_id', '=', 1)
->where('category_id', '=', 2)
->where(function($q) use($search){
if($search){
return $q->where(['group_name' => $search]);
}
});
how do I translate WHERE category_id = 1 AND category_id = 2 in the ::selectRaw query?
You can use the whereIn function.
$query = self::selectRaw((is_array($fields)?implode(", ",$fields):$fields))
->whereIn('category_id', [1,2])
->where(function($q) use($search){
if($search){
return $q->where(['group_name' => $search]);
}
});

How to use where not between in Laravel 5.5?

I am try
ing to get something like this
select * from `users`
inner join `settings`
on `users`.`id` = `settings`.`user_id`
and NOW() NOT BETWEEN quit_hour_start AND quit_hour_end
where `notification_key` != ''
and `device_type` = 'Android'
in eloquent. Does anyone try and get success to build this query in eloquent.
I know I can use \DB::select(DB::raw()); and get my result. But I want to use ie with Laravel eloquent method.
====== update comment for tried queries========
$androidUser = User::join('settings', function ($join) {
$join->on('users.id', '=', 'settings.user_id')
->where(DB::raw("'$currentTime' NOT BETWEEN quit_hour_start AND quit_hour_end"));
})
->where('notification_key', '!=', '')
->where('device_type' ,'=', 'Android')
->get();
$users = DB::table('users')
->whereNotBetween('votes', [1, 100]) // For one column
->whereRaw("? NOT BETWEEN quit_hour_start AND quit_hour_end", [$currentTime]) // Use whereRaw for two columns
->get();
https://laravel.com/docs/5.5/queries, or you can rewrite as to wheres

Laravel 5.4 subquery in where condition?

I want to write sub query inside where in condition and in subquery were condition, checking with parent query field.
as follows,
$query = DB::table('users');
$query->whereNotIn('users.id', function($query) use ($request) {
$query->select('award_user.user_id')
->from('award_user')
->where('award_user.user_id', 'users.id')
->where('award_user.award_id', $request->award_id);
});
Query is working fine, but
->where('award_user.user_id', 'users.id')
This line, users.id is not taking from parent query. If I enter manually number, then it is working correctly.
What is wrong with my query.. can you please suggest.
use whereRaw rather than where
$query = DB::table('users');
$query->whereNotIn('users.id', function($query) use ($request) {
$query->select('award_user.user_id')
->from('award_user')
->whereRaw('award_user.user_id', 'users.id')
->whereRaw('award_user.award_id = '.$request->award_id);
});

Using subqueries in Eloquent/Laravel

Here's the query in raw SQL:
SELECT *
FROM (
SELECT `characters`.`id`,`characters`.`refreshToken`,
`characters`.`name`,max(`balances`.`created_at`) as `refreshDate`
FROM `characters`
INNER JOIN `balances` ON `characters`.`id` = `balances`.`character`
WHERE `characters`.`refreshToken` IS NOT NULL
GROUP BY `characters`.`id`
) AS `t1`
WHERE `refreshDate` < '2017-03-29';
I've tested this in phpMyAdmin and it returns the expected results. However I'm using the Eloquent and Laravel libraries in my PHP app and I'm not sure how to approach this. How exactly do subqueries work in this case?
You can do a subquery as a table but need to create the subquery first and then merge the bindings into the parent query:
$sub = Character::select('id', 'refreshToken', 'name')
->selectSub('MAX(`balances`.`created_at`)', 'refreshDate')
->join('balances', 'characters.id', '=', 'balances.character')
->whereNotNull('characters.refreshToken')
->groupBy('characters.id');
DB::table(DB::raw("($sub->toSql()) as t1"))
->mergeBindings($sub)
->where('refreshDate', '<', '2017-03-29')
->get();
If that is your entire query you can do it without the subquery and use having() instead like:
Character::select('id', 'refreshToken', 'name')
->selectSub('MAX(`balances`.`created_at`)', 'refreshDate')
->join('balances', 'characters.id', '=', 'balances.character')
->whereNotNull('characters.refreshToken')
->groupBy('characters.id')
->having('refreshDate', '<', '2017-03-29');
You can use subqueries in Eloquent by specifying them as a closure to the where method. For example:
$characters = Character::where(function ($query) {
// subqueries goes here
$query->where(...
...
->groupBy('id');
})
->where('refreshDate', '<', '2017-03-29')
->get();
You have to chain your methods to the $query variable that is passed to the closure in the above example.
If you want to pass any variable to the subquery you need the use keyword as:
$characterName = 'Gandalf';
$characters = Character::where(function ($query) use ($characterName) {
// subqueries goes here
$query->where('name', $characterName)
...
->groupBy('id');
})
->where('refreshDate', '<', '2017-03-29')
->get();

Categories