Search code examples
phplaraveleloquentmany-to-manyrelationship

Eloquent get value Many to Many Relationship


This is my Vote model:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Vote extends Model
{
    public function user(){
      return $this->belongsTo('App\User');
    }

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

this is my Option model:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Option extends Model
{
    public function vote(){
      return $this->belongsTo('App\Vote');
    }

    public function users(){
      return $this->belongsToMany('App\User');
    }
}

The case is i want to get the users data from many to many relationship in Option model, but started from Vote model. So i get the options data in the Vote model first, then i get the users data in Option model (many to many)


Solution

  • Laravel has no native support for a direct relationship.

    I've created a package for cases like this: https://github.com/staudenmeir/eloquent-has-many-deep

    class Vote extends Model
    {
        use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
    
        public function users()
        {
            return $this->hasManyDeep(User::class, [Option::class, 'option_user']);
        }
    }