Question

I have a 'companies', 'certificaten' and 'companies_certificaten' table:

In my join table companies_certificaten i have 'companies_id' and 'certificaten_id'

This is part of my Company model

public function certificaten(){

      return $this->belongstoMany('Certificate', 'companies_certificaten','companies_id');

}

This is part of my Certificate model:

public function companies(){

     return  $this->belongstoMany('Company', 'companies_certificaten','certificaten_id');
}

Now i want to get all the certificaten:

 'certificaten' => Company::find($company_id)->certificaten

This is the full error i get:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'companies_certificaten.certificate_id' in 'field list' (SQL: select `certificaten`.*, `companies_certificaten`.`companies_id` as `pivot_companies_id`, `companies_certificaten`.`certificate_id` as `pivot_certificate_id` from `certificaten` inner join `companies_certificaten` on `certificaten`.`id` = `companies_certificaten`.`certificate_id` where `companies_certificaten`.`companies_id` = ?) (Bindings: array ( 0 => 48, ))

This part does not make sense of the error:

'companies_certificaten.certificate_id' in 'field list'

and

`companies_certificaten`.`certificate_id` as `pivot_certificate_id`

Nowhere in my models or tables i have "certificate_id" but i have a "certificaten_id"

Where does laravel get this "certificate_id" from? Not from me.

Was it helpful?

Solution

It is Eloquent default naming convention and you nowhere override it. This will do the job for you:

public function certificaten(){
  return $this->belongstoMany('Certificate', 'companies_certificaten','companies_id', 'certificaten_id');
}

then you will get company_id not found error, so update also this one:

public function companies(){
  return  $this->belongstoMany('Company', 'companies_certificaten','certificaten_id', 'companies_id');
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top