Saturday, March 18, 2017

Laravel 5.4 | Fetching data from Pivot Table

I have 4 tables in my database:

Table 1: Category

---|------
id | name
---|------
1  | Cars

In 'Category' model class I have defined the following relationship:

class Category {
    public function fields() {
        return $this->belongsToMany('App\Field');
    }
}

Table 2: Field

id | name
---|-------
1  | Make

In 'Field' model class I have defined the following relationship:

class Field {
    public function categories() {
        return $this->belongsToMany('App\Category');
    }
}

Table 3: Field_Options

field_id | value
---------|-------
1        | Audi
1        | BMW

In 'FieldOption' model class I have defined the following relationship:

class FieldOption extends Model
{
    public function field() {
        return $this->belongsTo('App\Field');
    }
}

Table 4: Category_Field

category_id | field_id
------------|-------
1           | 1

Now I need to fetch all the fields and field_options for category_id=1. How can I achieve this using Laravel?

Thanks!



via Rishab

Advertisement