Search code examples
laraveleloquenteloquent-relationship

Laravel eloquent: Combine belongsToMany Relation with hasOne Relation


is there any chance to combine belongsTo relation with an hasOne relationship?

I have for example this tables:

    users
    id
    username

    events
    id
    name

    states
    id
    name

    event_user
    id
    event_id
    user_id
    state_id

In event model is this function which returns an belongsToMany Relation. But I need to get the State Relation too.

In event model is this function which returns an belongsToMany Relation. But I need to get the State Relation too.

Has anyone an idea?

LinuTuris


Solution

  • You can consider using Pivot:

    namespace App\Models;
     
    use Illuminate\Database\Eloquent\Relations\Pivot;
    use Illuminate\Database\Eloquent\Relations\BelongsTo;
     
    class EventUser extends Pivot
    {
      
        public function state(): BelongsTo
        {
            return $this->belongsTo(State::class);
        }
    }
    

    Within User model:

    class User extends Model
    {
        public function events(): BelongsToMany
        {
            return $this->belongsToMany(Event::class)->using(EventUser::class)->withPivot('state_id');;
        }
    }
    

    Then:

    $user = User::find($id);
    
    foreach ($user->events as $event) {
       $state = $event->pivot->state;
    }
    

    Reference https://laravel.com/docs/10.x/eloquent-relationships#retrieving-intermediate-table-columns

    Another way is using hasMany:

    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Model;     
    use Illuminate\Database\Eloquent\Relations\BelongsTo;
         
    class EventUser extends Model
    {
      
        public function state(): BelongsTo
        {
           return $this->belongsTo(State::class);
        }
    
        
        public function event(): BelongsTo
        {
           return $this->belongsTo(State::class);
        }
    }
    

    In User model:

    class User extends Model
    {
       public function eventUsers(): BelongsToMany
       {
          return $this->hasMany(EventUser::class);
       }
    }
    

    Then:

    $user = User::with('eventUsers.event', 'eventUsers.state')->first();