samedi 27 août 2016

One-To-Many Relation with Pivot Table

I have 2 tables Manufacturers and Suppliers ,and they have Many-to-Many relation

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

  Schema::create('suppliers', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('location');
        $table->timestamps();
 ​ });

so i created a pivot table called "manufacturer_supplier" and it works fine.

Schema::create('manufacturer_supplier', function (Blueprint $table) {

$table->increments('id');
$table->integer('manufacturer_id')->unsigned()->index();
$table->integer('supplier_id')->unsigned()->index();
$table->timestamps();

$table->foreign('manufacturer_id')->references('id')->on('manufacturers')->onDelete('cascade');
$table->foreign('supplier_id')->references('id')->on('suppliers')->onDelete('cascade');
 });

My confusion comes from adding a new table "devices"

Schema::create('devices', function (Blueprint $table) {

$table->increments('id');
$table->string('serial')->unique();
$table->string('name');
​$table->integer('supplier_id')->unsigned()->nullable();
$table->integer('manufacturer_id')->unsigned()->nullable();
$table->text('notes')->nullable();
$table->timestamps();

$table->foreign('supplier_id')->references('id')->on('suppliers')->onDelete('cascade');
$table->foreign('manufacturer_id')->references('id')->on('manufacturers')->onDelete('cascade');
 });

where i want to have a one-to-many relation with each of suppliers and manufacturers , so i would have a select list of manufacturers and then populate the next list from with suppliers from Pivot table that relate to the selected manufacturer.

currently my "device"​ model has the following relations which it relate them to the original table not the pivot so it doesn't work

//5
public function manufacturer(){

return $this->belongsTo('App\Manufacturer');
}
//6

public function supplier(){

return $this->belongsTo('App\Supplier');
}

I haven't done that before so i'm curious to know what will be the best fix for this to work. Thanks a lot ,



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2boBg1c
via IFTTT

Aucun commentaire:

Enregistrer un commentaire