I'm trying to query database and make a filter in a closure function, my model (Simplified) looks like this:
Products:
id,
sale_id
Sales:
id,
provider_id
Provider:
id
I wanna all the products from a specific provider, so i've constructed this my query:
Product::with(array
('sale'=>function($query){
$query->where('provider_id', '=', 1);
})
)->get();
the problem is that the result contains the right products with the sale, and the wrong products with the sale null, like this:
[{
"id": 25,
"sale": null
},
{
"id": 26,
"sale": {
"id": 15,
"provider_id": 3
}
}]
products with sale:null are the products from another provider, I could filter them in memory, but I think there is a way to avoid the null results from the query, any clue?
Closures are anonymous functions that don't belong to any class or object. Closures don't have specified names and can also access variables outside of scope without using any global variables.
The whereBetween() method is a query builder chained alongside other Laravel query builders used to fetch data from the database. The whereBetween() method queries the database table to fetch rows of records from the database within a range of values.
DB::raw() is used to make arbitrary SQL commands which aren't parsed any further by the query builder. They therefore can create a vector for attack via SQL injection. Since the query builder is using PDO in the background, we know there is a way to bind parameters to our query so it will sanitize the bound variables.
Check if not null: whereNotNullSELECT * FROM users WHERE last_name IS NOT NULL; The equivalent to the IS NOT NULL condition in Laravel Eloquent is the whereNotNull method, which allows you to verify if a specific column's value is not NULL .
You need to add check about sale exists whereHas('sale') and apply condition about specific provider:
Product::whereHas('sale', function($query) {
$query->where('provider_id', '=', 1); }
)->get();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With