StuBlackett StuBlackett - 1 year ago 67
MySQL Question

Intermediate Tables & Laravel

I'm kind of new to the Eloquent (Pivot / Intermediate Tables) idea.

I am using Laravel 5.3 and the docs are making a little sense, but not enough. Unfortunatley!

I have a few scenarios that I'd like to try get data from...

I have the following DB Tables

  • Companies

  • Company_Offers

  • Offers

  • Company_Attributes

  • Attributes

In my scenarios the following is said of these DB Tables...

A company can have many offers

A company can have many attributes

An Offer can be associated with many companies

An attribute can be associated with many companies

I have created the 5 models to correspond to the 5 DB Tables.

I am trying to work out, How I get these relationships into my models?

Thank You!

Answer Source

You want to use the belongsToMany relationship. For example:

class Company extends Model
    public function offers()
        return $this->belongsToMany(App\Offer::class);

If you have setup your pivot table with company_id and offer_id this relationship will work automatically, and a pivot table of company_offer (singular version of model name in alphabetical order). If you didn't follow the naming convention you can specify the pivot table and foreign keys like so:

return $this->belongsToMany('App\Offer', 'Company_Offers', 'Company_ID', 'Offer_ID');