Laravel Eloquent Relationship - not fetching based on condition

Viewed 589

I wanted to fetch all id & name from User table which satisfies the condition , order_userId of Orders table == id of User table and order & uploadId columns of Orders table has the values false & null respectively. The below code returns all rows if data from User table without checking the where condition i've specified.. How can i fix this?

$data = User::with(['orders'=>function ($query){
            $query->where('order', false);
            $query->whereNull('uploadId');
        }])->pluck('name', 'id');

User Model

public function orders()
{
    return $this->belongsTo(Orders::class, 'order_userId', 'id');
}

The above code gives an output as below:

    {
        "id": 2,
        "name": "jen",
        "orders": null
    },
    {
        "id": 3,
        "name": "jos",
        "orders": null
    }
3 Answers

Try

$data = User::whereHas('orders', function ($query) {
    $query->where('order', false);
    $query->whereNull('uploadId');
})->pluck('name', 'id');

try This Solution:

The right relation is that, User has many orders.

User Model:

public function orders()
{
    return $this->hasMany(Orders::class, 'order_userId', 'id');
}

Checkout this also..

$data = User::whereHas('orders', function ($query) {
    $query->where([['order', false],['uploadId','>',0]]);
})->pluck('name', 'id');
Related