jeudi 24 mars 2016

laravel 5 pivot table with relational attributes

There are my tables:

operations:

  • id
  • name

users:

  • id
  • name

attributes:

  • id
  • name

attributes_values:

  • id
  • attribute_id
  • value

operations_users:

  • operation_id
  • user_id
  • attribute_value_id

One-to-many Models:

class Attribute extends Model
{
    public function values()
    {
      return $this->hasMany(AttributeValue::class);
    }
}
class AttributeValue extends Model
{    
    public function attribute()
    {
       return $this->belongsTo(Attribute::class);
    }
}

Many-to-many models:

class Operation extends Model
{
  public function users()
  {
    return $this->belongsToMany(User::class,
          'operations_users',
          'operation_id',
          'user_id')
        ->withPivot('attribute_id')
        ->withTimestamps();
  }
}
class User extends Model
{
  public function operations()
  {
    return $this->belongsToMany(Operation::class,
          'operations_users',
          'operation_id',
          'user_id')
        ->withPivot('attribute_id')
        ->withTimestamps();
  }
}

It works nice and can do almost everything I need but can't show attributes_values->value related to corresponding pivot entry. I'd like to retrieve data in a way like that:

  @foreach($operations->users as $user)
    {{ $user->attribute_value }}
    {{ $user->name }}
  @endforeach

(The code above don't work)

Still I can retrieve direct pivot data like that:

  @foreach($operations->users as $user)
    {{ $user->pivot->attribute_value_id }}
    {{ $user->name }}
  @endforeach

The question is - how to retrieve attribute_value in a most appropriate laravel / eloquent way? Is it possible without creating Model for pivot table (ie., class OperationUser extends Model)?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire