Home > OS >  Laravel Eloquent Relationship - not fetching based on condition
Laravel Eloquent Relationship - not fetching based on condition

Time:10-22

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 ($q){
            $q->where([
            'order'=>false,
            'uploadId'=>null]);
        }])->select('id', 'name')->get();

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
    }

CodePudding user response:

Try

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

CodePudding user response:

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');
}
  • Related