Skip to content

Laravel

rm edited this page Apr 17, 2016 · 2 revisions

Configuring the Eloquent model

Eavquent has been specially made for Eloquent and simplicity has been taken very serious as in any other Laravel related aspect. To add EAV functionality to your Eloquent model just define it like this:

class Company extends Model 
{
    use Devio\Eavquent\Eavquent;
}

That's it, we only have to include that trait in our Eloquent model!

Querying models

Eavquent tries to do everything in the same way Eloquent would normally do. When loading a model it internally creates a regular relationship for every entity attribute. This means we can query filtering by our registered attribute values like we would normally do when querying Eloquent relationships:

// city is an eav attribute
$companies = Company::whereHas('city', function ($query) {
    $query->where('content', 'Madrid');
})->get();

Attributes

Registering attributes

TODO

Registering your own value types

TODO

Allowing multiple values

TODO

Eager loading

Eavquent takes into account the powerful Eloquent eager loading system. When accessing to a Eavquent attribute in a Eloquent model, it will be loaded just in time as Eloquent does when working with relationships. However we can work with Eavquent using Eloquent eager loading for better performance and avoid the n+1 query problem. Eavquent has a special relationship name reserved for loading all the registered attributes. This relationship is called eav. When using eav for loading values, it will load all the attributes related to the entity we are playing with.

Lazy eager loading

Again, as any regular Eloquent relationship we can decide when to load our attributes. Do it as if you were normally loading a relationship:

$company->load('eav');
//
$company->load('city', 'colors');

Autoloading with $with

Eloquent ships with a $with which accepts an array of relationships that should be eager loaded. We can use it as well:

class Company extends Model
{
    use Devio\Eavquent\Eavquent;

    // Eager loading all the registered attributes
    protected $with = ['eav']; 
    // Or just load a few of them
    protected $with = ['city', 'colors'];
}