Hi there, I have three tables with relationships:
Event - id / title / etc...
Corporate - id / name / etc...
EventCorporate - id / event_id / corporate_id. ( the ID field might not be necessary but I'm keeping it for now )
And each model looks like the following:
class Event extends Model
{
protected $fillable = [
'title',
...
];
public function corporates_attending_events(){
return $this->hasMany(EventCorporate::class);
}
public function add_corporate( $corporate ){
$method = ( $corporate instanceof Corporate ) ? 'save' : 'saveMany';
$this->corporates_attending_events()->$method( $corporate );
}
// and more codes...
}
class Corporate extends Model
{
protected $fillable = [
'name',
'description',
'link',
'thumbnail',
'is_active'
];
// and more codes...
}
class EventCorporate extends Model
{
protected $table = 'event_corporate';
protected $fillable = [
'event_id',
'corporate_id',
'is_active'
];
public function event(){
return $this->hasOne(Event::class);
}
public function corporate(){
return $this->hasOne(Corporate::class);
}
// and more codes...
}
When I run the following unit test for Event:
public function it_adds_a_coporate_to_the_event()
{
$event = create_an_event();
$corporate = factory(Corporate::class)->create();
$event->add_corporate($corporate);
$this->assertEquals(1, $event->corporates_attending_events->count());
}
The unit test fails with the following error message:
Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1 no such column: event_id (SQL: update "corporates" set "event_id" = 1, "updated_at" = 2019-01-11 21:26:08 where "id" = 1)
The first thing I instantly noticed is that add_corporate(...) in Event motel is trying to update a wrong table - coporates. I thought corporates_attending_events() is pointing to event_corporate table due to the relationship created above... but it seems not.
Where is this thing coming from?
Did I set the relationships incorrectly?
The source code for save/saveMany is from Jeffrey's tutorial ( https://laracasts.com/series/phpunit-testing-in-laravel/episodes/6 ). For those who cannot access laracasts, the source files are here (https://github.com/laracasts/Hands-On-Testing-Workflow)
Thanks!