Multiple Relationship in Laravel 5

0

as I can make 2 tables with one, I explain, I have a table works and other projects, these two tables have in common a table called events, where I want to put as fk the id and type since they can be repeated the id (id 1 of works or projects for example). Previously I had it related only to the works table, but I had to add projects, so I added the field type to events to be able to differentiate. How would the relationship in the migration and the model be? Thanks

    
asked by Maurikius 12.01.2018 в 21:20
source

2 answers

1

In your events model, you have to make the relationship of the two tables, it would be something like this.

Depending on the type of relationship the table has, one by one, one by many, many by many, you would have to change the hasMany clause by the one that corresponds to the type of relationship

  <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Events extends Model
{
    //
    protected $table = 'events';
    protected $primaryKey = 'id';
    protected $fillable = ['id','campo1', 'campo2', 'campo3', 'campo4'];

    public function works(){
        //Este sería tu modelo works que apunta a dicha tabla
        return $this->hasMany('App\Works', 'id');
    }

    public function projects(){
        //Este sería tu modelo projects que apunta a dicha tabla
        return $this->hasMany('App\Projects','id');
    }
}
    
answered by 12.01.2018 в 21:50
0

Thanks, so I have the model, but with belong to

public function work()
{
    return $this->belongsTo('App\Work', 'parent_id', 'parent_type');
}

// Relaciono el evento con su proyecto
public function project()
{
    return $this->belongsTo('App\Project', 'parent_id', 'parent_type');
}

Regarding the migration, as would be adding 2 tables in the reference.

public function up()
{
    Schema::create('events', function (Blueprint $table) {
        $table->increments('id');
        $table->date('date');
        $table->time('time');
        $table->string('place', 200);
        $table->string('city', 100);
        $table->integer('parent_id')->unsigned();
        $table->foreign('parent_id')->references('id')->on('works')->onDelete('cascade')->onUpdate('cascade');
        $table->integer('parent_type')->unsigned();
        $table->foreign('parent_type')->references('id')->on('works')->onDelete('cascade')->onUpdate('cascade');
        $table->timestamps();
    });
}
    
answered by 12.01.2018 в 22:45