Home > Enterprise >  Summary table for the model
Summary table for the model

Time:08-31

There is a model ObjectType and a model GuestOptions

I want to create a pivot table, I do this

public function up()
{
    Schema::create('object_type_options', function (Blueprint $table) {
        $table->unsignedBigInteger('object_type_id');
        $table->unsignedBigInteger('guest_option_id');
        $table->foreign('object_type_id')->references('id')->on('object_types')->onDelete('cascade');
        $table->foreign('guest_option_id')->references('id')->on('guest_options')->onDelete('cascade');
        $table->primary(['object_type_id','guest_option_id']);
    });
}

In the model I define the relation ObjectType , but there is no result

public function options()
{
    return $this->belongsToMany(GuestOptions::class,'object_type_options');
}

What am I doing wrong?

CodePudding user response:

Can give two basic and quick solutions.

public function options()
{
     return $this->belongsToMany(GuestOptions::class,'object_type_options','object_type_id','guest_option_id');
}

you can also use the relation more clearly like below. but need to change some attributes in the database.

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

And Table need to change

public function up()
{
    //table name changed
    Schema::create('guest_options_object_type', function (Blueprint $table) {
        $table->unsignedBigInteger('object_type_id');//actual table name
        $table->unsignedBigInteger('guest_options_id'); //actual table name
        $table->foreign('object_type_id')->references('id')->on('object_types')->onDelete('cascade');
        $table->foreign('guest_options_id')->references('id')->on('guest_options')->onDelete('cascade');
        $table->primary(['object_type_id','guest_option_id']);
    });
}
  • Related