Juliatzin
Juliatzin

Reputation: 19725

Get only consumers from an operation that has a user attached with Eloquent in Laravel 8

I have a list of meters:

ID, name, user_id 
1, meter1, 4
2, meter2, NULL
3, meter3, 5

and consumers from an Operation:

Operation Class:

public function consumers(): HasMany
    {
        return $this->users()->role(User::CONSUMER);
    }

Relations:

I would like to get only consumers from an operation that has a user attached.

In my example, it should just return meter 1 and 3.

I just don't know how to do it with Eloquent.

Upvotes: 0

Views: 35

Answers (1)

rfpdl
rfpdl

Reputation: 964

Try this:

Updated as requested by topic owner:

public function consumers(): HasMany 
{
    return $this->users()->role(User::CONSUMER)->whereHas('meter', function($query) {
        $query->whereNotNull('user_id'); 
    }); 
}

My personal answer:

$consumers = Operation::with(['consumers' => function($query) {
    $query->whereHas('meter', function($qry) {
        $qry->whereNotNull('user_id');
    });
}])->get();

//Or better:

Class User extends Model
{
    ...

    public function existing_meters()
    {
        return $this->hasMany(Meter::class)->whereNotNull('user_id');
    }
}

//then you can use it:

$consumers = Operation::with('consumers.existing_meters')->get();

Upvotes: 2

Related Questions