kaiza's avatar
Level 1

laravel relation ship

I'm asking this because I'm new to laravel and PHP in general, I want to build up a relation ship between:

users
domains
user_domains

A user has one domain, but one domain can be assigned to many different users. Should I follow this approach has-one-through?

laravel.com/docs/10.x/eloquent-relationships#has-one-through

Meaning:

A domain HasManyThrough() users (using user_domains)

A user HasOneThrough domain (using user_domains)

0 likes
4 replies
kaiza's avatar
Level 1

@shaungbhone I've already created my models, using oneToMany makes no sense, since a user will only hold one domain, but a domain can be associated to more users.

Domain:

public function users()
{
    return $this->hasManyThrough(
        User::class,
        UserDomain::class,
        'domain_id',
        'id',
        'id',
        'user_id'
    );
}

User:

public function domain()
{
    return $this->hasOneThrough(
        Domain::class,
        UserDomain::class,
        'user_id',
        'id',
        'id',
        'domain_id'
    );
}

But how can I create a new relation (UserDomain)?

    $domain = Domain::find(1);
    User::find(1)->domain()->create($domain);

already tried:

    $domain = Domain::find(1);
    User::find(1)->domain()->associate($domain);

None of this worked.

kaiza's avatar
Level 1

If I would use hasMany() on the Domain model and belongsTo on the User model this might work ( I think it shlould be hasOne on user model if I stick to this way approach).

But I'm looking for a way using hasOneThrough, how to "attach" the domain to the user model.

Please or to participate in this conversation.