Laravel orWhere usage - laravel

I have the following query:
$foundItem = ItemDrop::where('zone_id',$this->user->zone_id)
->where('find_rate','>=',$itemChance)
->orderBy('find_rate','desc')
->take(1);
In my database, I set zone_id = "-1" if I want the ItemDrop to be available in all zones.
So I've been thinking how I can add it to my query..
$foundItem = ItemDrop::where('zone_id',$this->user->zone_id)
->orWhere('zone_id',"-1")
->where('find_rate','>=',$itemChance)
->orderBy('find_rate','desc')
->take(1);
but it doesn't feel right and probably will not work correctly, because I have 2 Wheres and the OrWhere should be included only with the first where: where('zone_id',$this->user->zone_id).
How I can get all records of ItemDrop with zone_id -1 AND $this->user->zone_id?
How my DESIRED query would look like without Laravel:
SELECT * FROM ItemDrops WHERE( zone_id = "-1" || zone_id = $this->user->zone_id) && find_rate >= $itemChance

Try this:
$foundItem = ItemDrop::where(function($query){
$query->where('zone_id',$this->user->zone_id)
->orWhere('zone_id',"-1");
})->where('find_rate','>=',$itemChance)
->orderBy('find_rate','desc') ->take(1);

You can use an anonymous function in orWhere to do this. Try something like this:
$foundItem = ItemDrop::where('zone_id',$this->user->zone_id)
->orWhere( function ($query) {
$query->where('zone_id',"-1");
})
->orderBy('find_rate','desc')
->take(1);
Hope it helps...

Related

Laravel 8 - How I do where clause in table added with join

Hi I want to know how can i do this query in Laravel 8 , I tried adding the join clause but not work as expected, i need join clause? Or maybe there is another form to do it. I search others examples but i donĀ“t see anythat help me. The query is the next:
DB::table('escandallo_p as esc')
->select("esc.material", "esc.referencia", "esc.ancho", "esc.proveedor", "esc.punto",
"esc.precio", "esc.consumo", "esc.veces", "esc.001", "esc.002", "esc.003", "esc.004",
"esc.005", "esc.006", "esc.007", "esc.008", "esc.009", "esc.010", "esc.011", "esc.um", "esc.merma", "esc.importe", "esc.tipo", "esc.xtalla", "esc.fase",
DB::raw("(select anulado from prototipos_p as p where p.prototipo = '".$scandal[0]->prototipo."' and p.tipo = 'c' and p.referencia = esc.referencia )"),
// ignore
//original query "(select anulado from prototipos_p as p where p.prototipo = ",$request->prototipo," and p.tipo = 'c' and p.referencia = esc.referencia ) as 'anulado'",
// "(select clase from prototipos_p as p where p.prototipo = ",$request->prototipo," and p.tipo = 'c' and p.referencia = esc.referencia ) as 'clase'")
//Converted query ->select('pro.anulado')->where('pro.prototipo', $request->prototipo)
// ->where("p.prototipo", "=", $request->prototipo)
->where("esc.id_escandallo", "=", $request->id_escandallo)
->where("esc.id_version", "=", $request->version)
->orderBy("id","asc")
->get();
!!!! I need to pass the esc.referencia to the sub select query
The second select is the conversion of the select inside "" ( i know this is wrong is only for explain it).
Thank you in advance for any suggestion.
Best regards
EDIT: I can solve my problem with DB::raw, but if anyone know others methos are welcome!
You need to pass callback to the join query to add the extra query to the laravel's join method,
Example from Laravel Doc:
DB::table('users')
->join('contacts', function ($join) {
$join->on('users.id', '=', 'contacts.user_id')
->where('contacts.user_id', '>', 5);
})
->get();
It is explained in Laravel's doc, Advanced Join Clauses
There is Subquery support too Subquery Joins,
Eg:
$latestPosts = DB::table('posts')
->select('user_id', DB::raw('MAX(created_at) as last_post_created_at'))
->where('is_published', true)
->groupBy('user_id');
$users = DB::table('users')
->joinSub($latestPosts, 'latest_posts', function ($join) {
$join->on('users.id', '=', 'latest_posts.user_id');
})
->get();
These two might help you to achieve what you are trying
After test joins, joinSub, whereIn and other forms of doing this, I solved my problem using the DB::raw():
DB::table('escandallo_p as esc')
->select('parameters',....,
DB::raw("(SELECT column //(ONLY ONE)
FROM table
WHERE column = '".$parameter."' ...) AS nombre"),
)
->where('column', "=", $parameter)
->orderBy("id","asc")
->get();

Laravel 8, whereRelation take the where value condition from model

i'm using whereRelation but i do not know
how to take the where value condition from the base model
I have tried this code:
Item::with('unit','stock')->whereRelation('stock', 'stock', '<', 'items.min_stock');
and query result in debugger :
select * from `items` where exists (select * from `stocks` where `items`.`id` = `stocks`.`id_item` and `stock` < 'items.min_stock')
The query result i wanted :
select * from `items` where exists (select * from `stocks` where `items`.`id` = `stocks`.`id_item` and `stock` < `items`.`min_stock`)
'items.min_stock' it become like a string, How can i solve this ?
Otherize you can use whereHas method, example below:
Item::with('unit', 'stock')->whereHas('stock', function ($query) {
$query->where('stock', '<', DB::raw('items.min_stock'))
});
I found solution for my code
i change my code like this and it's works
Item::with('unit','stock')->whereRelation('stock', 'stock', '<', DB::raw('items.min_stock'));
thanks to #Vildan Bina for the answer
Try using whereRaw
Item::with('unit','stock')->whereRelation('stock', function (Builder $query) {
$query->whereRaw('stock < items.min_stock'); // semicolon
});

db::raw adding is null in query

I am trying to use laravel query builder like:-
$users = DB::table('baid_collection')
->select(DB::raw('sum(total) as total_collect,collection_limit_c'))
->join('users_cstm', 'baid_collections.assigned_user_id', '=', 'users_cstm.id_c')
->where(DB::raw("assigned_user_id = '$userId' and DATE(date_entered)=CURDATE()"))
->groupBy('assigned_user_id')
->get();
This query should be like
select sum(total) as total_collect,collection_limit_c from `baid_collections` inner join `users_cstm` on `baid_collections`.`assigned_user_id` = `users_cstm`.`id_c` where assigned_user_id = '15426608-3ea5-f299-7a80-601bd06be2d9' and DATE(date_entered)=CURDATE() group by `assigned_user_id`
But last run query showing me
select sum(total) as total_collect,collection_limit_c from `baid_collection` inner join `users_cstm` on `baid_collections`.`assigned_user_id` = `users_cstm`.`id_c` where assigned_user_id = '15426608-3ea5-f299-7a80-601bd06be2d9' and DATE(date_entered)=CURDATE() is null group by `assigned_user_id`
In query is null giving problem i dont want is null in query
Use whereRaw instead of where like
$users = DB::table('baid_collections')
->select(DB::raw('sum(total) as total_collect,collection_limit_c'))
->join('users_cstm', 'baid_collections.assigned_user_id', '=', 'users_cstm.id_c')
->whereRaw("assigned_user_id = '{$userId}' and DATE(date_entered)=CURDATE()")
->groupBy('assigned_user_id')
->get();
It's creating a problem due to where needs atleast two parameters and you are just passing one parameter
Check this if it helps, write whereDate instead of add date in raw query.
if you are not using Carbon, you can also use php date("Y-m-d"), method to get date
DB::table('baid_collection')
->select(DB::raw('sum(total) as total_collect,collection_limit_c'))
->join('users_cstm', 'baid_collections.assigned_user_id', '=', 'users_cstm.id_c')
->where(DB::raw("assigned_user_id = '$userId'"))
->whereDate("date_entered", "=", Carbon::now()->toDateString())
->groupBy('assigned_user_id')->get();
You can try this
$users = DB::table('baid_collection')
->select(DB::raw('sum(total) as total_collect,collection_limit_c'))
->join('users_cstm', 'baid_collections.assigned_user_id', '=', 'users_cstm.id_c')
->where(DB::raw("assigned_user_id = '$userId' and DATE(date_entered) = '".date('Y-m-d')."'"))
->groupBy('assigned_user_id')
->get();

Refactor Laravel Query

I have a query that I have built, and I am trying to understand how I can achieve the same thing but in one single query. I am fairly new to Laravel and learning. Anyway someone could help me understand how I can achieve what I am after?
$activePlayerRoster = array();
$pickupGames = DB::table('pickup_games')
->where('pickupDate', '>=', Carbon::now()->subDays(30)->format('m/d/Y'))
->orderBy('pickupDate', 'ASC')
->get();
foreach ($pickupGames as $games) {
foreach(DB::table('pickup_results')
->where('pickupRecordLocatorID', $games->recordLocatorID)
->get() as $activePlayers) {
$activePlayerRoster[] = $activePlayers->playerID;
$unique = array_unique($activePlayerRoster);
}
}
$activePlayerList = array();
foreach($unique as $playerID) {
$playerinfo = DB::table('players')
->select('player_name')
->where('player_id', $playerID)
->first();
$activePlayerList[] = $playerinfo;
}
return $activePlayerList;
pickup_games
checkSumID
pickupDate
startTime
endTime
gameDuration
winningTeam
recordLocatorID
pickupID
1546329808471
01/01/2019
08:03 am
08:53 am
50 Minute
2
f47ac0fc775cb5793-0a8a0-ad4789d4
216
pickup_results
id
checkSumID
playerID
team
gameResult
pickOrder
pickupRecordLocatorID
1
1535074728532
425336395712954388
1
Loss
0
be3532dbb7fee8bde-2213c-5c5ce710
First, you should try to write SQL query, and then convert it to Laravel's database code.
If performance is not critical for you, then it could be done in one query like this:
SELECT DISTINCT players.player_name FROM pickup_results
LEFT JOIN players ON players.player_id = pickup_results.playerID
WHERE EXISTS (
SELECT 1 FROM pickup_games
WHERE pickupDate >= DATE_FORMAT(SUBDATE(NOW(), INTERVAL 30 DAY), '%m/%d/%Y')
AND pickup_results.pickupRecordLocatorID = recordLocatorID
)
Here I'm assuming you know what you're doing with this dates comparison, because it looks weird to me.
Now, let's convert it to Laravel's code:
DB::table('pickup_results')
->select('players.player_name')->distinct()
->leftJoin('players', 'players.player_id', '=', 'pickup_results.playerID')
->whereExists(function ($query) {
$query->select(DB::raw(1))
->from('pickup_games')
->where('pickupDate', '>=', Carbon::now()->subDays(30)->format('m/d/Y'))
->whereRaw('pickup_results.pickupRecordLocatorID = recordLocatorID');
})
->get();
Basically, I would reduce the query to its SQL variant to get directly at its core.
The essence of the query is
select `x` FROM foo WHERE id IN (
select distinct bar.id from bar join baz on bar.id = baz.id);
This can be interpreted in Eloquent as:
$thirtyDaysAgo = Carbon::now()->subDays(30)->format('m/d/Y');
$playerIds = DB::table('pickup_games')
->select('pickup_games.player_id')
->join(
'pickup_results',
'pickup_results.pickupRecordLocatorID',
'pickup_games.recordLocatorID')
->where('pickupDate', '>=', $thirtyDaysAgo)
->orderBy('pickupDate', 'ASC')
->distinct('pickup_games.player_id');
$activePlayers = DB::table('players')
->select('player_name')
->whereIn('player_id', $playerIds);
//>>>$activePlayers->toSql();
//select "player_name" from "players" where "player_id" in (
// select distinct * from "pickup_games"
// inner join "pickup_results"
// on "pickup_results"."pickupRecordLocatorID" = "pickup_games"."recordLocatorID"
// where "pickupDate" >= ? order by "pickupDate" asc
//)
From the resulting query, it may be better to refactor the join as relationship between the Eloquent model for pickup_games and pickup_results. This will help to further simplify $playerIds.

Laravel 5.6: how to create a subquery using Query Builder

I would like to reproduce following mySQL query using Laravel query builder:
*SELECT SUM(scores) FROM (SELECT scores FROM player_games WHERE player_id = 1 ORDER BY id DESC LIMIT 2) scores
Any suggestions?
Here the solution:
$sub = playerGame::where('player_id',1)->where('scores','>',0)->limit(2)->orderBy('id','desc');
$count = DB::table( DB::raw("({$sub->toSql()}) as sub") )
->mergeBindings($sub->getQuery())
->sum('scores');
return $count;
Use fromSub():
$sub = playerGame::select('scores')
->where('player_id', 1)
->where('scores', '>', 0)
->limit(2)
->orderBy('id','desc');
$sum = DB::query()->fromSub($sub, 'scores')->sum('scores');
$responce= DB::table('player_games')->where('player_id',1)->sum('amount');
dd(collect($responce)->sortByDesc('id')->take(2));
please cheack this one.....i try it's work....and add use DB;in the top of controller....

Resources