Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel query with closure

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?

like image 604
Padron Leandro Avatar asked Sep 18 '16 22:09

Padron Leandro


People also ask

What is closure in laravel?

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.

How do I use whereBetween in laravel?

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.

How write raw SQL query in laravel?

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.

Where IS NOT NULL eloquent?

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 .


1 Answers

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();
like image 153
Adiasz Avatar answered Oct 07 '22 08:10

Adiasz