Many-to-Many with values in between

I have an EAV-like structure in my database:

Entity ( id, name ), EntityAttribute ( id, entity_id, attribute_id, value ), Attribute( id, name)

I use standard approach described in the documentation to declare many to many models relationship:

class Entity extends ... {
    public function initialize() {
        $this->hasManyToMany( 'id', 'EntityAttribute', 'entity_id', 'attribute_id', 'Attribute', 'id', array(
            'alias' => 'Attributes'
        ) );
    }

    public function getAttributes( $parameters = null ) {
        return $this->getRelated( 'Attributes', $parameters );
    }
}

class EntityAttribute extends ... {
    public function initialize() {
        $this->belongsTo( 'entity_id', 'Entity', 'id' );
        $this->belongsTo( 'attribute_id', 'Attribute', 'id' );
    }
}

class Attribute extends ... {
}

It works fine if I try to receive attributes for an entity:

$entity = Entity::findFirst(1);
$attributes = $entity->getAttributes();

The problem is that getAttributes() method returns only attributes names, but I need to retrieve attribute name + value for a certain entity. How can I achive it?



81.8k

You can use toArray():

$entity = Entity::findFirst(1);
$values = $entity->toArray();

$entity->toArray(); returns data from Entity table. I need to get a combination of data from Attributes and EntityAttributes tables.