Manual Many to Many relations due to 3 way pivot plus other data.
Created 7 years ago by edsterSo I was doing some reading up on other places, and the below implementation is best suggestion and should be working, but i can't figure out why for the life of me it doesn't work. I actually have 4 streams, but am only working with 3 of them at the moment and can't get it working for them, so lets focus on that.
I basically have to manually deal with the many to many relation manually. I have done this with 3 streams, building, buildings_sections and sections.
Saving buildings works fine, saving sections works fine, its relating them together that is crapping out.
Building model has
/**
* Get the sections for the building if there are any
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function sections()
{
return $this->hasMany('Emange\StrataModule\Strata\BuildingSectionsModel', 'building_id');
}
Sections model has
/**
* Get the sections for the building if there are any
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function buildings()
{
return $this->hasMany('Emange\StrataModule\Strata\BuildingSectionsModel', 'section_id');
}
buildings_sections model looks like this
public function building()
{
return $this->belongsTo('Emange\StrataModule\Strata\Building\BuildingModel');
}
public function section()
{
return $this->belongsTo('Emange\StrataModule\Strata\Section\SectionModel');
}
Now, I have a sync that I'm trying to do,
if($model->save()){
//Set the section or sections for this model and save
if (count(get_object_vars($building->Sections)) > 1) {
$sections = [];
foreach ($building->Sections as $section){
$sections[] = str_slug($section, '-');
}
$model->sections()->saveMany($sectionRepository->findAllBySlugs($sections)->all());
} else{
$model->sections()->save($defaultSection);
}
}
The save many and save is whats crapping out. It is trying to update the sections model, not save to the buildings_sections model, and I can't figure out why. below is the error.
"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'building_id' in 'field list' (SQL: update `martello_group_strata_sections` set `sort_order` = 6, `updated_at` = 2017-11-14 19:37:14, `updated_by_id` = 1, `building_id` = 37 where `id` = 6) ◀"
Help?
So by using the intermediate model I can insert the records, but I was hoping to be able to use saveMany.
Still hoping someone can point out to me why it hates me