ravipw1801
1 year ago

Cascade deleting with Polymorphic relationship

Posted 1 year ago by ravipw1801

3 types of posts Business, Social & Nature. All these have some attributes in common Country, City & Range. These common attributes have polymorphic relation with all three types of postscountriable, citiable & rangeable.

BusinessPosts table structure:

public function up()
    {
        Schema::create('businesses', function (Blueprint $table) {
            $table->increments('id');
            $table->string('brand');
            $table->integer('user_id')->unsigned();
            $table->integer('phone');
            $table->string('email');
            $table->string('url');
            $table->text('description')->nullable();
            $table->tinyInteger('status')->default(0);
            $table->timestamps();
        });
    }

BusinesPost Model:

class BusinessPost extends Model
{

    public function ranges()
    {
        return $this->morphToMany('App\Range','rangeable');
    }

    public function countries()
    {
        return $this->morphToMany('App\Country','countriable');
    }

    public function user()
    {
        return $this->belongsTo('App\User');
    }

}

Country Model:

class Country extends Model
{
    protected $fillable = ['name'];

    public function businesses()
    {
        return $this->morphedByMany('App\Business', 'countriable');
    }

    public function socials()
    {
        return $this->morphedByMany('App\Social', 'countriable');
    }

    public function natures()
    {
        return $this->morphedByMany('App\Nature', 'countriable');
    }
}

country table structure:

public function up()
    {
        Schema::create('countries', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }

countriable table structure:

public function up()
    {
        Schema::create('countriables', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('country_id');
            $table->integer('countriable_id');
            $table->string('countriable_type');
            $table->timestamps();
        });
    }

So, my question is, if the user deletes a post, all of its relationships should get detached, or in case the user deletes its account, all his posts, along with relationships should get deleted?

Till now everything is working fine except the deletion part!

Please sign in or create an account to participate in this conversation.