Maarten Kuijper
Maarten Kuijper

Reputation: 354

Laravel relations and keys for accessing the data

I have just set up my first relation in an eloquent model.

class Member extends Model
{
    public function person()
    {
        return $this->hasOne(Person::class, 'id', 'person_id');
    }

It was a bit confusing at first, because the docs would use member_id in the person table.. but for my db structure this would make no sense. Anyways I was struggling to show records in an index or form, because I was trying to access person info like this:

$member->mobile

Instead of

$member->person->mobile

I would love to get rid of this 'person' in between, just as I had with left joins. Is there a laravel way of doing this? without using left joins. Every time I try to google it, I get the usual eloquent relation stuff. Maybe there is an option that already exists... If so I might be writing unnecessary functions, otherwise I might even switch back to using left joins and scopes. If I keep using this, it will get a lot worse.. for example

$member->person->address->street  

or even 5 in a row which I kinda want to avoid

Upvotes: 0

Views: 54

Answers (1)

georaldc
georaldc

Reputation: 1940

I may be wrong, but I don't think this is possible other than creating a new class that aggregates all properties of whatever model you want + properties of relationships. You could also update your model class and override the __get() method and react accordingly, but that sounds like a lot of work too (make sure to call the parent implementation too).

The need to specify the relation name actually makes your code easier to read since $member->mobile would look more like a property of your member class. Plus it allows you add additional constraints before retrieving your relation[s]

https://laravel.com/docs/5.4/eloquent-relationships#querying-relations

Upvotes: 1

Related Questions