mercredi 26 octobre 2016

Acessing $this from within an eloquent relationship

I have a property model that looks something like this:

class Property extends Model
{
    public function accessUsers()
    {
        $access_id = $this->access_id

        return $this->hasMany('App\User')
            ->whereHas('access', function ($query) use ($access_id) {
                $query->where('id', $access_id);
            });
    }
}

To be clear: A Property has many Users. Users has a relationship to a model called Access. This query should only result with users who have a reltionship with Access where Access.id is equal to Property.access_id

The problem I'm running into is when $this->access_id is called it's returning a null value (even when a value exists). dd($this) returns a Property object but with the attributes all empty. I'm inclined to belive that at this point of the code Eloquent/QueryBuilder hasn't queried the DB to retrieve the attribute values yet.

Is it possible to pull in the values at this point? Can I structure this in a different way that will give me the same results? I'd like to eager load these accessUsers() from a controller like so: Property::with('accessUsers')->get()



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire