That is a pivot table, so you'll need to define the extra columns on that pivot table, and then can access them through the 'pivot' keyword.. See docs: https://laravel.com/docs/5.2/eloquent-relationships#many-to-many (scroll down to 'Retrieving Intermediate Table Columns' section)
Mar 14, 2016
3
Level 1
Get data from Relation Tables
If I have properties table, and other 2 tables
-
property_characteristics
- property_id (i.e. 1)
- characteristic_id (i.e. 5 - join with default_characteristics)
- value (i.e. 3 - aka 3 rooms)
-
default_characteristics
- id (i.e. 5)
- name (i.e. rooms)
How can I get the number of rooms (value from property_characteristics) for a property if I set up all belongs_to and has_many in models?
$property = Properties::find(1);
Level 1
I solved with:
public function characteristics()
{
return $this->belongsToMany('Proactiv\DefaultCharacteristic', 'property_characteristics', 'property_id', 'characteristic_id')
->withPivot('value');
}
And method:
public function getCharacteristic($name)
{
$value = $this->characteristics
->where('name', $name)
->first();
if(!$value) return '?';
return $value
->pivot
->value;
}
Please or to participate in this conversation.