I have theses tables :
chevals :
- id
- name
courses :
- id
- name
horses_races :
- id
- cheval_id
- course_id
For no french speakers, cheval = horse, and course = race.
I want to make a relation ship between horses and races.
Example : horses 1 has done 3 races, and race #4 has 15 horses
I create horses like this :
$cheval = Cheval::firstOrCreate([
'name' => $name->textContent,
'sexe' => $sexe,
'age' => $age
]);
$cheval->save();
I need to know how to do for the horses_race table at the saving moment and after that to something like :
race->get()
echo all_horses_for_these_race();
or
horse->get();
echo all_races_for_theses_horse();
I tried this
$cheval->courses()->save(['course_id' => $race->id, 'cheval_id' => $cheval->id]);
But I get :
IlluminateDatabaseEloquentRelationsBelongsToMany::save(): Argument #1 ($model) must be of type IlluminateDatabaseEloquentModel, array given, called in /var/www/html/turfix/app/Http/Controllers/CourseController.php on line 234
My question is just : How to save the relation data ?
2
Answers
Laravel DOCS – Many To Many Relationships
You can use the
attach()
method to many-to-many relationship.To get all horses for a race,
To get all races for a horse,