How can I build has single query in laravel - laravel

$tadaydate = ddate('m/d/Y');
$value1 = value_table::where('value_1', $tadaydate)->get();
$value2 = value_table::where('value_2', $tadaydate)->get();
$value3 = value_table::where('value_3', $tadaydate)->get();
$value4 = value_table::where('value_4', $tadaydate)->get();
$value5 = value_table::where('value_5', $tadaydate)->get();
Is there any chance to check with single query?

You can use the "->whereIn()" function I believe.
$value_array = ['value1',...,'value5'];
$value_table->whereIn($tadaydate, $value_array)->get;

You can combine then:
$query = value_table::where('value_1',$tadaydate)
->orWhere('value_2',$tadaydate)
->orWhere('value_3',$tadaydate)
->orWhere('value_4',$tadaydate)
->orWhere('value_5',$tadaydate)
->get()
You should use where instead of orWhere to connect the wheres with an AND instead of an OR
To simplify it in a loop:
$columns = 7;
$query = value_table::query();
for ($i = 1;$i <= $columns;$i++) {
$query = $query->orWhere('value_'.$i,$tadaydate);
}
$values=$query->get();
However you will have much more success if you normalise your table:
table
-----------
id | more columns
value_table
------------
id | table_id (fK) | value
And two models Table and ValueTable . That way (assuming proper eloquent setup) you can just do:
$tableRow = Table::whereHas("value", function ($q) use ($tadaydate) {
return $q->where("value",$tadaydate);
})->get();

You can use whereIn for this. In whereIn you can pass your array like this:
$values_list = [$val1,$val2,$val3];
$data = YourModel::whereIn($tadaydate, $values_list)->get();

You should try this:
$tadaydate=ddate('m/d/Y');
$result = value_table::where('value_1',$tadaydate)
->orWhere('value_2',$tadaydate)
->orWhere('value_3',$tadaydate)
->orWhere('value_4',$tadaydate)
->orWhere('value_5',$tadaydate)
->get();
Updated Answer
$user_list = value_table::where(function($query) use ($tadaydate){
$query->where('value_1', =, $tadaydate);
$query->where('value_2', =, $tadaydate);
$query->where('value_3', =, $tadaydate);
$query->where('value_4', =, $tadaydate);
$query->where('value_5', =, $tadaydate);
})
->get();

Related

Eloquent - Join a Subquery

I have a complicated query that I would like to translate either in Eloquent ORM or with the Query Builder for a Laravel site, but I can't do it, can someone help me?
Here is my SQL query
SELECT opp_id, risk_study.rst_id, risk_study.rst_status
FROM opportunity
LEFT JOIN risk_study ON risk_study.rst_id =
(SELECT risk_study_quote_vehicle.rst_id
FROM risk_study_quote_vehicle
INNER JOIN quote_vehicle ON quote_vehicle.quv_id = risk_study_quote_vehicle.quv_id
INNER JOIN quote ON quote.quo_id = quote_vehicle.quo_id
WHERE quote.opp_id = opportunity.opp_id
ORDER BY risk_study_quote_vehicle.rst_id DESC
LIMIT 0,1)
WHERE 1 = 1
AND opportunity.per_id_process = '5'
AND opportunity.opp_locked = '1'
Here is my solution.
But this query does not retrieve values from the risk_study table.
$opportunities = Opportunity::select('opp_id', 'risk_study.rst_id', 'risk_study.rst_status')
->leftJoin('risk_study', function ($join) {
$join->on('risk_study.rst_id', '=', DB::raw('"SELECT risk_study_quote_vehicle.rst_id FROM risk_study_quote_vehicle INNER JOIN quote_vehicle ON quote_vehicle.quv_id = risk_study_quote_vehicle.quv_id INNER JOIN quote ON quote.quo_id = quote_vehicle.quo_id WHERE quote.opp_id = opportunity.opp_id ORDER BY risk_study_quote_vehicle.rst_id DESC LIMIT 0,1"'));
})
->where([
['per_id_process', 5],
['opp_locked', 1],
])
->get();
Finally, I wrote the query and it works ! Thanks !
$opportunities = Opportunity::query()
->select(
'opp_id',
'risk_study.rst_id',
'risk_study.rst_status'
)
->from('opportunity')
->leftJoin('risk_study', function ($join) {
$join->where('risk_study.rst_id', function ($sub) {
$sub->select('risk_study_quote_vehicle.rst_id')
->from('risk_study_quote_vehicle')
->join('quote_vehicle', 'quote_vehicle.quv_id', 'risk_study_quote_vehicle.quv_id')
->join('quote', 'quote.quo_id', 'quote_vehicle.quo_id')
->whereColumn('quote.opp_id', 'opportunity.opp_id')
->orderByDesc('risk_study_quote_vehicle.rst_id')
->limit(1);
});
})
->where('opportunity.per_id_process', '5')
->where('opportunity.opp_locked', '1')
->get();
You should be able to use a Closure as the second parameter of where() inside your join Closure.
I don't think Laravel's query builder supports the LIMIT 0,1 statement.
I don't know why you need WHERE 1 = 1, but you should be able to use whereRaw for that.
When you're done, the result looks very alike a formatted SQL query.
$opportunities = Opportunity::query()
->select(
'opp_id',
'risk_study.rst_id',
'risk_study.rst_status'
)
->from('opportunity')
->leftJoin('risk_study', function ($join) {
$join->where('risk_study_quote_vehicle.rst_id', function ($sub) {
$sub->select('risk_study_quote_vehicle.rst_id')
->from('risk_study_quote_vehicle')
->join('quote_vehicle', 'quote_vehicle.quv.id', 'risk_study_quote_vehicle.quv_id')
->join('quote', 'quote.quo_id', 'quote_vehicle.quo_id')
->where('quote_opp_id', 'opportunity.opp_id')
->orderByDesc('risk_study_quote_vehicle.rst_id')
->limit(1);
});
})
->whereRaw('1 = 1')
->where('opportunity.per_id_process', '5')
->where('opportunity.opp_locked', '1')
->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....

How do I return this query in blade view

$semester01 = '1';
$session01 = '5';
$level01 = '200';
$results = DB::table('results')
->join('departments', 'results.DepartmentID', '=', 'departments.DepartmantID')
->join('subjects', 'results.SubjectID', '=', 'subjects.SubjectID')
->groupBy('matricno')
->selectRaw('results.matricno as matricno, sum(tnu) as sum, sum(subjects.SubjectValue) as sum2')
->where('results.Level', $level01)
->where('results.Semester', $semester01)
->where('results.SessionID', $session01)
->where('departments.DepartmantID', '17')
->get();
//return $arrayed;
$results2 = DB::table('results')
->join('departments', 'results.DepartmentID', '=', 'departments.DepartmantID')
->join('subjects', 'results.SubjectID', '=', 'subjects.SubjectID')
->groupBy('matricno')
->selectRaw('results.matricno as matricno, sum(tnu) as sumr2, sum(subjects.SubjectValue) as sum2r2')
->where('results.Level', $level01)
->where('results.Semester', $semester01)
->where('results.SessionID', $session01)
->where('departments.DepartmantID', '7')
->get();
The above code is supposed to return a group of students with distinct results alongside the various departments.
Result1 and result2 are supposed to be joined together, with matricno being the distinct field. I want to display the result in this form. Merging both results into one tabular form.
matricno | sum | sum2 | sumr2 | sum2r2
You can use merge() method for merge those collections like;
$merged_result = $results->merge($results2)
You can return a view with some data as follows
return view('viewname', ['results' => $results, 'results2' => $results2]);
return view('yourview')->with(['results' => $results, 'results2' => $results2]);

Laravel 4 eloquent WHERE with AND and OR?

How do I say WHERE (a=x AND b=y) OR (c=z AND d=j)
For x , y , z .. are variables .
How can i do that with eloquent ?
for multiple where statements use:
$result = Model::whereRaw('(a = ? and b=?) or (c=? and d=?)', ['x','y','z','j'])->get();
You can achieve this by passing a closure into the where() function of the query builder. This is covered in the advanced wheres section of the docs http://laravel.com/docs/5.0/queries#advanced-wheres
$results = MyModel::where(function($query) {
$query->where('a', 'x')
->where('b', 'y');
})->orWhere(function($query) {
$query->where('c', 'z')
->where('d', 'j');
})->get();

Resources