skip to Main Content

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


  1. Laravel DOCS – Many To Many Relationships

    DB::transaction(function () {
        $cheval = Cheval::firstOrCreate([...]);
        $course = Course::findOrFail($courseId);
        $cheval->courses()->attach($course);
    })
    
    Login or Signup to reply.
  2. You can use the attach() method to many-to-many relationship.

    $cheval->courses()->attach($race->id);
    

    To get all horses for a race,

    $race = Course::find($raceId);
    $horses = Cheval::whereHas('courses', function ($query) use ($raceId) {
        $query->where('course_id', $raceId);
    })->get();
    

    To get all races for a horse,

    $horse = Cheval::find($horseId);
    $races = Course::whereHas('chevals', function ($query) use ($horseId) {
        $query->where('cheval_id', $horseId);
    })->get();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search