I have 3 tables in my Database
# Items
id - name
----------
1 - Item A
2 - Item B
3 - Item C
.
# Traits
id - name
----------
1 - Color
2 - Grade
3 - Size
.
# Values
id - item_id - trait_id - value
----------
1 - 1 - 1 - red
1 - 2 - 1 - green
1 - 3 - 1 - red
1 - 1 - 2 - 90%
1 - 2 - 2 - 45%
1 - 3 - 2 - 80%
1 - 1 - 3 - 4 inches
1 - 2 - 3 - 5 inches
1 - 3 - 3 - 9 inches
In Laravel, I could get all items with their traits and values using "belongsTo" [$this->belongsTo('App\Traits','trait_id');] in Value model to get the results like so :
--- Item A
Color: red
Grade: 90%
Size: 4 inches
--- Item B
Color: green
Grade: 45%
Size: 5 inches
.. etc
from code like this :
$items = Items::get();
foreach ($items as $item) {
echo '<h2>'.$item->name.'</h2>';
foreach ($item->values as $value) {
echo '<b>'.$value->trait->name . '</b>: ';
echo $value->value . '<br>';
}
}
However, what I couldn't do is that I need to filter these results, for examples, I only need Items that its color is "red" and its grade bigger than 70% ?
If you don't use Larave, feel free to write it in pure mysql queries, I may find a way to do it in Laravel when I get the idea.. Thank you
idserves no purpose in the values table (which is, btw, a poor choice of name). A good tip, if using an EAV model, is to construct separate tables for each data type.