Home > Net >  Access Data From Pivot Table On Model
Access Data From Pivot Table On Model

Time:01-27

I need to get data from a pivot table.

I have 2 models: sites, technologies. These 2 models are related by a pivot table called site_technology, this table has 2 columns called col_a, col_b that I would like to access. Right now I have this:

class Site{
  public function technologies(){
    return $this->hasMany('App\Models\Technology')
  }
}

My question is, how do I link the 2 models, and how do I access the data on that piovt table with eloquent?

CodePudding user response:

I see this question a lot, the best way I have found to do this is with the following code.

class Site{
  public function technologies(){
    return $this->belongsToMany(Technology::class, 'PIVOT_TABLE')->withPivot('column_a', 'column_b')
  }
}

This will allow you to get the data by doing this.

$data = Site::first()->technologies->first()->pivot->column_b

I hope this helped!

  •  Tags:  
  • Related