Eloquent Laravel - Migration and Model

Asked

Viewed 51 times

0

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

Example :

A resale for having no or n addresses, and an address may have only one resale.

This relationship would result in a resale_address tableinserir a descrição da imagem aqui

I’m using version 5.7 of Laravel.

1 answer

1


We need to define the third table, which is the dynamic table. Follow 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();
    });
}

Define the 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';
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.