简体   繁体   中英

Eloquent all records relationship

I'm trying to build an alternative relationship that returns all records instead of only related records. I have tried returning a query builder, but that doesn't work, it must be a relationship. What should I return to make this work?

public function devices()
{
    if ($this->admin) {
        // return all devices relationship instead
    } else {
        return $this->belongsToMany('Device', 'permissions');
    }
}

Fiddle: https://implode.io/XXLGG8

Edit: I'd like to continue building the query in most cases, not just get the devices.

The devices() function in your model is expected to return a relation, you shouldn't add the if statement there. Make your devices() function like this:

public function devices()
{
    return $this->belongsToMany('Device', 'permissions');
}

In your User model add a new function:

public function getDevices() {
    if($this->admin === true) {
        return Device::all(); 
    } 

    return $this->devices();
}

Now you can do:

$admin->getDevices(); // will return all devices
$user->getDevices(); // will return only relations

I actually went a slightly different way and used a scope:

protected function scopeHasAccess($query, User $user)
{
    if ($user->admin) {
        return $query;
    }

    return $query->join('permissions', 'permissions.device_id', "devices.id")
        ->where('permissions.user_id', $user->user_id);
}

Add devices accessor method to the User model and implement your logic there.

public function getDevicesAttribute() {
    if ($this->admin) {
        return Device::all();
    }
    return $this->getRelationValue('devices');
}

See updated " fiddle ".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM