Laravel 8, whereRelation take the where value condition from model - laravel

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

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

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 Query Builder and Eloquent query builder add an odd phrase when I try to build the query on the fly?

I am attempting to build a query on the fly depending upon what is entered in a form. When I do so, I check what the sql statement is in the Console. I have OR and AND contitions, so I use a call back to build the query. the SQL statement that results is:
select `id`, `activity_name`, `activity_name_web`, `year`, `season`, `sex`,
`active_on_web`, `begin_active_on_web`, `end_active_on_web`, `begin_age`,
`end_age`, `begin_date`, `end_date` from `activities` where (season='fall'
OR season='summer' is null) order by `begin_date` desc, `activity_name` asc
limit 25 offset 0 []
notice the words "is null". I can't determine how this phrase is being added.
The Code:
$qry_where = "1";
$arry_Season = array();
if($this->a_fall)
$arry_Season[] = "LOWER(`season`)='fall'";
if($this->a_spring)
$arry_Season[] = "LOWER(`season`)='spring'";
if($this->a_summer)
$arry_Season[] = "LOWER(`season`)='summer'";
if($this->a_winter)
$arry_Season[] = "LOWER(`season`)='winter'";
if(count($arry_Season)>0) {
$qry_where = $arry_Season[0];
if(count($arry_Season)>1){
array_shift($arry_Season);
foreach($arry_Season as $season){
$qry_where .= " OR " . $season;
}
}
}
$activities = Activity::select('id','activity_name','activity_name_web','year','season', 'sex', 'active_on_web',
'begin_active_on_web', 'end_active_on_web', 'begin_age', 'end_age', 'begin_date','end_date')
->where(function($query) use ($qry_where) {
if($qry_where == "1")
$query->where('id','>',0);
else {
$query->where(DB::raw($qry_where));
}
})
->orderBy('begin_date','desc')->orderBy('activity_name','asc')
->paginate(25);
So, if the users checks the box labelled "fall", I add it to the query builder.
so - Where is the phrase "is null" coming from.
select `id`, `activity_name`, `activity_name_web`, `year`, `season`, `sex`,
`active_on_web`,`begin_active_on_web`, `end_active_on_web`, `begin_age`,
`end_age`, `begin_date`, `end_date` from `activities`
where (season='fall' OR season='summer' is null)
order by `begin_date` desc, `activity_name` asc limit 25 offset 0 []
btw, say I check fall and summer, then I ddd($qry_where) just before I build the query, I get this:
"LOWER(`season`)='fall' OR LOWER(`season`)='summer'"
I also need to mention that I am using a livewire component.
thanks for the help in advance.
#apokryfos thank you for your quick answer. It was driving me crazy. It seems when I passed a variable into the ->where(DB::raw()), it evaluated the variable too late for the ->when() to see that the variable contained a comparison?
In any case, I tweeked the solution that #apokryfos a bit and came up with the following:
$activities = Activity::select('id','activity_name','activity_name_web','year','season', 'sex', 'active_on_web',
'begin_active_on_web', 'end_active_on_web', 'begin_age', 'end_age', 'begin_date','end_date',
'cost_member','cost_non_member')
->when(count($seasons) > 0, function($query) use ($seasons) {
$query->whereIn('season', $seasons);
})
->orderBy('begin_date','desc')->orderBy('activity_name','asc')
->paginate($this->items_on_page);
the ->whereIn() could not process the "DB::raw('LOWER(season)', $seasons)" as suggested. If i want to make sure that the data in the [activities].[season] column, I will either have to make sure the seasons are input into the table in lower case, or do a ->select(DB:raw('LOWER(season)') in the SQL statement. I like the first option.
thank you again for your input apokryfos
You did a where(<raw query>) which defaults to do a WHERE <raw query> is not NULL since WHERE assumes a comparison. Here's what I think is a more concise version of your query:
$seasons = array_filter([
$this->a_spring ? 'spring' : null,
$this->a_summer ? 'summer' : null,
$this->a_fall ? 'fall' : null
$this->a_winter ? 'winter' : null
]);
$activities = Activity::select('id','activity_name','activity_name_web','year','season', 'sex', 'active_on_web',
'begin_active_on_web', 'end_active_on_web', 'begin_age', 'end_age', 'begin_date','end_date')
->when(count($seasons) > 0, function($query) use ($seasons) {
$query->whereIn(DB::raw('LOWER(season)'), $seasons);
})->when(count($seasons) == 0, function ($query) {
$query->where('id', > 0); // Not sure you need this part
})
->orderBy('begin_date','desc')->orderBy('activity_name','asc')
->paginate(25);

How to select min and max in laravel

I want to convert this code in laravel.
SELECT MAX(date_start) AS DateStart,MIN(date_end) AS DateEnd FROM DBTest
And I try this code
$data = DB::table('DBTest')
->select(max('date_start'), min('date_end')))
->get();
Return Error: max(): When only one parameter is given, it must be an array
I am using laravel 5.2, and SQLyog as database
I am confuse in syntax please help me
You can't use functions in select statement, but you can use raw SQL :
$data = DB::table('DBTest')
->select(\DB::raw('MIN(date_start) AS DateStart, MAX(date_end) AS DateEnd'));
->get();
You can do it like this:
For the max start date:
max = DB::table('DBTest')->select('date_start')->orderBy('date_start', 'desc')->first();
For min end date:
min = DB::table('DBTest')->select('date_end')->orderBy('date_end', 'asc')->first();
You have to use something called selectRaw method in Laravel in order to achieve this result. Chaining method like ->max('columnA')->min('columnB') will not work. So, here is the solution:
$data = DB::table('DBTest')
->selectRaw('MAX(date_start) AS DateStart, MIN(date_end) AS DateEnd')->get();
Try MIN() and MAX() functions in the sql query.
$data = DB::table('DBTest')
->select(\DB::raw('MIN(date_start) AS startDate, MAX(date_end) AS endDate'));
->get();

Laravel orWhere usage

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...

Resources