2

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
    }
Rémy
  • 335
  • 2
  • 7

3 Answers3

4

Try

$data = User::whereHas('orders', function ($query) {
    $query->where('order', false);
    $query->whereNull('uploadId');
})->pluck('name', 'id');
Rémy
  • 335
  • 2
  • 7
0

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');
}
Shahid Rasheed
  • 371
  • 4
  • 10
  • i tried this. Still it returns all rows of datas that even don't satisfy the where condition i specified on orders relation. Means, i wanted to get only the rows of users table that satisfy the condition `order` = `false` & `uploadId`=`null` –  Oct 22 '21 at 10:30
0

Checkout this also..

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