Using hasMany on a pivot/intermediate model

Posted 4 months ago by tmcguire

Hey everyone!

Quick question about intermediate/pivot models, and how to hook up relationships from those models.

I have four models:

  • User
  • Organization
  • OrganizationUser, which is the relationship between Users and Organizations. This can be thought of as a "membership" – a user can have many organizations, and organizations can have many users.
  • Content, which is specific to the OrganizationUser/membership. One "membership" can have many pieces of content.

I've set up OrganizationUsers to haveMany Content, and also set up that Content belongsTo OrganizationUsers – at least, I tried to, anyhow! I'd anticipate being able to do something like this:

$user->organizations()->find(...)->relationship->content()->create([
    '...' => '...',
])

This does create a Content object on the database, but it doesn't associate it with the OrganizationUser at all. I'm sure that I'm missing something obvious when defining the relationships.

Here are the relevant sections of the above four models:

User.php

class User extends Authenticatable
{
    ...

    public function organizations()
    {
        return $this->belongsToMany(Organization::class)   
            ->using('App\OrganizationUser')
            ->as('relationship')
            ->withPivot([
                'role',
                ...
            ])
            ->withTimestamps();
    }

    ...
}

Organization.php

class Organization extends Model
{
    ...

    public function users()
    {
        return $this->belongsToMany(User::class)
            ->using('App\OrganizationUser')
            ->as('relationship')
            ->withPivot([
                'role',
                ...
            ])
            ->withTimestamps();
    }

    ...
}

OrganizationUser.php

class OrganizationUser extends Pivot
{
    ...

    public function content()
    {
        return $this->hasMany(Content::class);
    }

    ...
}

Content.php

class Content extends Model
{
    ...

    public function user()
    {
        return $this->belongsTo(OrganizationUser::class);
    }

    ...
}

Is there a better/different way I should be going about this? Any steering in the right direction would be so appreciated!

Please sign in or create an account to participate in this conversation.