laraveleloquentrelationshipdatabase-relations

laravel eloquent relationships between 3 model


actually i have two kind of users which has two different table (user and seller table). i have comment table with this fields:

   Schema::create('comments', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned()->nullable();
        $table->foreign('user_id')->references('id')->on('users');                         
        $table->integer('parent_id')->unsigned()->default(0);
        $table->text('comment_text');
        $table->integer('commentable_id')->unsigned();
        $table->string('commentable_type');
        $table->timestamps();
    });

how can I add seller_id to this table? if seller wants to response to a user comment.

same issue for message table.


Solution

  • Actually the good practice is you must add a role field in the user table that determines the user is a user or seller. But if you want to keep your table like that you don't need to add seller_id, just use one to many polymorphic relations. Change your comments table schema like this :

    Schema::create('comments', function (Blueprint $table) {
        $table->increments('id');                    
        $table->integer('parent_id')->unsigned()->default(0);
        $table->text('comment_text');
        $table->integer('commentable_id')->unsigned();
        $table->string('commentable_type');
        $table->timestamps();
    });
    

    Then in the user and seller model, you must add the relationship method like this :

    public function comments()
    {
        return $this->morphMany('App\Comment', 'commentable');
    }
    

    And in the comment model like this :

    public function commentable()
    {
        return $this->morphTo();
    }
    

    Then you can get the seller comment like this :

    $seller = App\Seller::find(1);
    $seller->comments;
    

    And to save the comment from the seller you can use this :

    $seller = App\Seller::find(1);
    
    $comment = $seller->comments()->create([
        'comment_text' => 'A new comment.',
        // Add other field
    ]);