Laravel hasManyThrough

后端 未结 1 769
情深已故
情深已故 2020-12-09 04:06

I\'m struggling to get my head around a hasManyThrough concept with laravel. I have three tables:

Bookings
    -id (int)
    -some other fields

Meta
    -id         


        
相关标签:
1条回答
  • 2020-12-09 04:47

    hasManyThrough is not the way at all. It works only for relations like this:

    A hasMany/hasOne B, B hasMany/hasOne C, then A hasManyThrough C (through B)
    

    What you have here is a many to many (belongsToMany), with meta being the pivot table.

    So you can do this (assuming meta is table name, Booking and MetaType are models):

    // Booking model
    public function meta()
    {
      return $this->belongsToMany('MetaType', 'meta', 'booking_id', 'metatype_id')
            ->withPivot([ ARRAY OF FIELDS YOU NEED FROM meta TABLE ]);
    }
    

    Then you can access all associated MetaType:

    $booking->meta; // collection of MetaType models
    

    query it like this (eager loading):

    $booking = Booking::with(['meta' => function ($q) {
    
      // query related table
      $q->where('someFieldOnMetaTypeTable', 'someValue')
    
        // and / or pivot table
        ->wherePivot('someFieldOnMetaTable', 'anotherValue');
    
    }])->first();
    

    or set constraints on the related table to filter the Booking:

    $booking = Booking::whereHas('meta', function ($q) {
    
      // query related table
      $q->where('someFieldOnMetaTypeTable', 'someValue')
    
        // and / or pivot table
        ->where('meta.someFieldOnMetaTable', 'anotherValue');
    
    })->first();
    

    Note: wherePivot works only when you eager load the relationship, so you can't use it in whereHas closure.

    0 讨论(0)
提交回复
热议问题