Casper Witting
Casper Witting

Reputation: 73

Laravel stuck with eloquent issue

I've been stuck with this eloquent relationship for a while. (I'm using laravel 5.2)

A user can have multiple certificates which individually have an aircrafttype. However, it is possible to have a "blank" certificate that doesn't have an aircrafttype.

My goals is to call $user->certificates, and retreive all the certificates of the user with the according aircrafttypes.

I have the following models.

    User
    id
    ...


    Aircrafttype
    id
    name 


    Certificate
    id 
    name


    CertificateUser 
    id
    certificate_id
    aircrafttype_id
    user_id

Thanks in advance!

Upvotes: 0

Views: 133

Answers (1)

James
James

Reputation: 16339

You just need to add a relationship between your User model and your CertificateUser model.

By the sounds of it, a user can have many certificates - so you would want to use the hasMany relationship. Because you have a column called user_id in the CertificatUser table, you can simply set up the relationship like this (inside your User model:

public function certificates()
    {
        return $this->hasMany('App\CertificateUser');
    }

You can now access this through the $user object with $user->certificates;

Upvotes: 1

Related Questions