Eloquent Laravel - Migration e Model

0

Could someone give me an example of how I make a relationship in the migration and model, where this relationship results in a table with external ids.

Example:

A reseller by having no or n addresses, and an address can only have one resale.

This relationship would result in a resale_address table

I'm using version 5.7 of Laravel.

    
asked by anonymous 10.10.2018 / 19:08

1 answer

1

We need to define the third table, which is the PivotTable. Here is an example

Now, set the following scheme in the migration file.

 public function up()
{
    Schema::create('category_product', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('category_id')->unsigned();
        $table->integer('product_id')->unsigned();
    });
}

Set relationships:

class Category extends Model
{
  public function products(){
    return $this->belongsToMany(Product::class);
  }
}

The other

class Product extends Model
{
public function categories()
{
    return $this->belongsToMany(Category::class);
}
}

To create a product, do

 public function create(Request $request)
{
    $product = new Product;
    $product->name = 'God of War';
    $product->price = 40;

    $product->save();

    $category = Category::find([3, 4]);
    $product->categories()->attach($category);

    return 'Success';
}
    
10.10.2018 / 19:33