mercredi 21 novembre 2018

Laravel Query builder in many to many Relationship

Let's consider that I have a model called Sportman and another one Sport who are linked via a pivot table : many to many relationship.

A sample code for their migrations.

    # Sportmans migration
    Schema::create('sportsmans', function (Blueprint $table) {
        $table->increments('id');
        $table->string('firstname');
        $table->string('lastname');
    });

    # Sports migration
    Schema::create('sports', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('description');
    });

Here is their relationship in models :

    # Defining association in Sportsman model
    public function sports()
    {
        return $this->belongsToMany( Sport::class, 'sportsman_has_sports', 'person_id', 'sport_id' );
    }

    # Defining association in Sports model
    public function sportsman()
    {
        return $this->belongsToMany( Sportsman::class );
    }

How can I, using Laravel with Eloquent, get the sportsman that play :

  1. Only "Footbal"
  2. Box or "Swimming"
  3. Either "Tennis and Basket-ball


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire