Ternary Laravel Relationship

Asked

Viewed 92 times

0

I’m creating a polling system where I have the following tables. A poll has several options. An option belongs only to a poll. A user can vote in multiple polls, but one option per poll. Soon I made

Model User

public function options(){
  return $this->belongsToMany(Option::class);
}

Model Survey

public function options(){
  return $this->hasMany(Option::class);
}

Model Option

public function survey(){
  return $this->belongsTo(Survey::class,'survey_id');
}

public function users(){
  return $this->belongsToMany(User::class);
}

Knowing which option he voted on I do a search for that option and display the polls he’s participating in, I’d also like to display the amount of total votes she has so far, bringing all the options from that poll, taking each option of this and adding up how many user_id each has, it would be very complicated, so I decided to make a ternary relationship.

        Schema::create('option_user', function (Blueprint $table) {
        $table->bigIncrements('id');

        $table->unsignedBigInteger('option_id');
        $table->unsignedBigInteger('user_id');
        $table->unsignedBigInteger('survey_id');


        $table->foreign('user_id')
              ->references('id')
              ->on('users')->onDelete('cascade');


        $table->foreign('option_id')
              ->references('id')
              ->on('options')->onDelete('cascade');

      $table->foreign('survey_id')
            ->references('id')
            ->on('survey')->onDelete('cascade');

        $table->softDeletes();
        $table->timestamps();
    });
}

How do I insert and search the elements of this table, example search for the Surveys that this user voted for.

1 answer

1


Browser other questions tagged

You are not signed in. Login or sign up in order to post.