vendredi 11 novembre 2016

Multiple relationship between two entities in Laravel 5.3?

I have these two tables that are already has many-to-many relationship using a pivot table, below are the migrations :

Journal Table

public function up()
    {
        Schema::create('journal', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title', 255);
            $table->text('abstract');
            $table->text('file');
            $table->integer('id_edition')->unsigned();
            $table->timestamps();
        });
    }

Users table :

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->enum('level', ['admin', 'author']);
            $table->timestamps();
        });
    }

Pivot table :

public function up()
    {
        Schema::create('penulis', function (Blueprint $table) {
            // Create tabel penulis
            $table->integer('id_user')->unsigned()->index();
            $table->integer('id_journal')->unsigned()->index();
            $table->timestamps();

            // Set PK
            $table->primary(['id_user', 'id_journal']);

            // Set FK penulis --- user
            $table->foreign('id_user')
                  ->references('id')
                  ->on('users')
                  ->onDelete('cascade')
                  ->onUpdate('cascade');

            // Set FK penulis --- journal
            $table->foreign('id_journal')
                  ->references('id')
                  ->on('journal')
                  ->onDelete('cascade')
                  ->onUpdate('cascade');
        });
    }

Now for some reasons it seems that I have to create another relation between these to table (users and journal) with one-to-many relationship, users has many journals. I'd like to add "OriginalPoster" field at the journal table referencing to users id. Is it possible ?

Users model :

public function journal()
    {
        return $this->belongsToMany('App\Journal', 'penulis', 'id_user', 'id_journal')->withTimeStamps();
    }

Journal model :

public function user()
    {
        return $this->belongsToMany('App\User', 'penulis', 'id_journal', 'id_user');
    }



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire