Finding the exact occurrence of Laravel - laravel

Products::whereIn('category_id', ['223', '15', '20'])
->where('active', 1)
->get();
How can I fix this example so that it finds the exact occurrence of category_id = 223 and 15 and 20 and also necessarily active = 1?

It makes no sense to look for exactly category_id = 15, 20 and 223, it can only be one...
But, if you still want that, your query is nearly there, you can do:
Products::where('category_id', '223')
->where('category_id', '15')
->where('category_id', '20')
->where('active', 1)
->get();
But, again, that should return an empty Collection. whereIn is a simple IN in SQL, that means it is an OR for all the values you want.

Use from this group. Because, maybe you use OR condition in future. Therefore, your condition will not work correctly.
For example
Products::query()->where(function ($query){
$query->where('category_id', '223')
->where('category_id', '15')
->where('category_id', '20');
})->where('active', 1)
->get();
Explain of query above will work like that:
Select * from products where (category_id = 223 and category_id = 15 and category_id = 20) and active = 1

Related

I want to find the value who exist in array

I have 2 queries and I would like to know the elements (date_debut) of the second query which exists in the first query (dateincal). The elements of the second query can appear one or more times in the first query.
once the dates (date debut) (dateincal) have been found i want to be able to then retrieve also the other information for the element found
$feries = Jourferie::Select('dateincal', 'description')
->where('dateincal', '>=', Carbon::now()->startOfMonth())
->where('dateincal', '<=', Carbon::now()->endOfMonth())
->get();
$plannings = Planning::Select('date_debut', 'id', 'agent_id', 'site_id')
->where('id', '!=', 0)
->where('statut', 'provisoire')
->get();
I don't know if that way can help you:
foreach($feries as $ferie){
$myresult = $plannings->contains('date_debut',$ferie->dateincal)
/* do things */
}

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.

Counting columns with if conidition in query

Counting only columns in which, Buy_Rate is more than Sell_Rate.
My query is not resulting as per expected, it is resulting me wrong.
$user_id = Auth::user()->id;
$losing_trades_count = FinalTrade::where('user_id', '=', $user_id)->where('buy_rate', '<', 'sell_rate')->get()->count();
Inverse: If sell_rate is more than buy_rate then only, count the columns.
You can use whereColumn
$losing_trades_count = FinalTrade::where('user_id', '=', $user_id)
->whereColumn('buy_rate', '<', 'sell_rate')
->count();
Also there is no need to call get() when you need count() from query builder
laravel eloquent where don't support comparing columns. so you need use raw SQL in order to compair two columns. you can do something like,
$user_id = Auth::user()->id;
$losing_trades_count = FinalTrade::where('user_id', '=', $user_id)->whereRaw('buy_rate < sell_rate')->get()->count();
hope this helps!

Querying related table data with Eloquent

i have a problem trying to get records from a model based on a related table.
I have two tables one called leads and one called recycle_logs, my app will basically send the same record in the leads table like once a month, and when it does so i'll store a new record in recycle_logs.
The problem is that i need to select all leads with a specific campaign_id value and that have a specific status that is different from invalid, so far so good, now the problem is i need to get them only if they don't have any recycleLogs associated with them OR if the last recycleLog associated with that particular lead is older than 30 days ago for instance.
What i currently have looks somewhat like this.
$leads = $this->leadModel->where(Lead::CAMPAIGN_ID, $this->campaignID)
->where(Lead::DUPLICATED, Lead::DUPLICATED_NO)
->where(Lead::LEAD_STATUS, "!=" ,Lead::LEAD_STATUS_INVALID)
->orderBy(Lead::CREATED_AT, 'desc')
->with(
['leadRecyclingLog' => function($query) {
$query->where(LeadRecyclingLog::CREATED_AT, '<', (new Carbon())->subDays($this->configRecyclingDays))
->orWhere(LeadRecyclingLog::ID, null);
}]
)
->get();
What exactly am i doing wrong? It always selects the same number of records regardless of me adding or removing recycleLogs
I've managed to get it done through a raw SQL query which i'll post below in case it helps anyone, i'd still like to know how to do it in Eloquent/Query Builder.
SELECT * FROM `leads` LEFT JOIN `lead_recycling_logs` ON `leads`.`guid` = `lead_recycling_logs`.`original_lead_guid` WHERE `leads`.`campaign_id` = :campaignID AND `leads`.`duplicated` = 0 AND `leads`.`lead_status` != :invalidStatus AND (`lead_recycling_logs`.`id` IS NULL OR `lead_recycling_logs`.`created_at` < :recyclingDate) ORDER BY `leads`.`created_at` DESC
Try this:
$leads = $this->leadModel->where(Lead::CAMPAIGN_ID, $this->campaignID)
->where(Lead::DUPLICATED, Lead::DUPLICATED_NO)
->where(Lead::LEAD_STATUS, "!=" ,Lead::LEAD_STATUS_INVALID)
->orderBy(Lead::CREATED_AT, 'desc')
->where(function($q) {
$q->whereHas('leadRecyclingLog', function($q) {
$q->where(LeadRecyclingLog::CREATED_AT, '<', (new Carbon())->subDays($this->configRecyclingDays));
})
->orWhereHas('leadRecyclingLog', '<', 1); // Where count of the relationship is smaller than 1
})->get();
I assumed the first part of the query is working well (up until the relationship).
What you're looking for is ->whereHas(relationship), not ->with(relationship). ->with(relationship) will attach the associated results to the original model (the query for the original model will not be affected by ->with()). ->whereHas(relationship) filters the original model by the condition.
Got it to work through #devk 's help
$leads = $this->leadModel->where(Lead::CAMPAIGN_ID, $this->campaignID)
->where(Lead::DUPLICATED, Lead::DUPLICATED_NO)
->where(Lead::LEAD_STATUS, "!=" ,Lead::LEAD_STATUS_INVALID)
->orderBy(Lead::CREATED_AT, 'desc')
->where(function($q) {
$q->whereHas('leadRecyclingLog', function($q) {
$q->where(LeadRecyclingLog::CREATED_AT, '<', (new Carbon())->subDays($this->configRecyclingDays));
})
->doesntHave('leadRecyclingLog', 'or');
})->get();

Laravel search for the close results

My app has an option to battle another player.
In order to match a player with another, I created a database field named score in my users table.
My goal is to match user with a another random user who is already SEARCHING for a battle. Both of the users has to be on +-100 score difference.
For example, user with score of 100 can battle players with score of 0-200.
I'm trying to search for all of the available options, but couldn't get how to do this.
Currently, I just output the first one in SEARCHING mode.
$pvp = PvpBattle::where('mode','=','SEARCHING')
->first();
How I can get all PvpBattle objects where the associated player1_id has +- 100 score difference from $this->me->score?
Try This code
WhereHas('users') is the user relation between PvpBattle and user
$minScore = $this->me->score - 100;
$maxScore = $this->me->score + 100;
$pvp = PvpBattle::where('mode','=','SEARCHING')
->WhereHas('users', function ($query) use ($minScore, $maxScore){
$query->Where(function ($subQuery) use ($minScore, $maxScore){
$subQuery->orWhere('score', '<=', $maxScore)
->orWhere('score', '>=', $minScore);
});
})
->first();
First find the score of player one to $scoreA or use $this->me->score
Then
$opp_list=PvpBattle::where('mode','=','SEARCHING')->Where(function($query)
{
$query->where('score', '>=', $scoreA -100)
->orwhere('score', '<=', $scoreA+100);
})
->get();
This gets all the players in mode searching with condition score +-100. first() returns the first result from the table.
How are you going to handle two requests at the same time pointing to the same user?
User A should be not returned as a result.
Add ->where('user_id', '!=', $user_id) to query
Use a join with the users table to filter the result by the score of the related user.
$pvps = PvpBattle::join('users', 'users.id', '=', 'pvpbattle.user_id')
->where('pvpbattle.mode','=','SEARCHING')
->where('users.score', '>=', $this->me->score - 100)
->where('users.score', '<=', $this->me->score + 100)
->get()
;

Resources