Laravel morph relationship

后端 未结 1 708
忘掉有多难
忘掉有多难 2021-02-06 05:39

I have a question regarding saving polymorphic relationships in Laravel. This is the model i would like to create in laravel.

A shop has many products, and a pr

相关标签:
1条回答
  • 2021-02-06 06:10

    First of all add a back relation to Shop from Product Model

        class Shop extends Model
        {
          public function products()
          {
            return $this->hasMany('App\Product');
          }
        }
    
        class Product extends Model
        {
          public function shop()
          {
            return $this->belongsTo('App\Shop');
          }
    
          public function productable()
          {
            return $this->morphTo();
          }
        }
    
        class Event extends Model
        {
          public function product()
          {
            return $this->morphOne('App\Product', 'productable');
          }
        }
    
    

    Now, I am not sure why you are trying to make an empty event and add it to all the products, but still if you want to do it for whatever use cases... please follow the below approach... :)

    $shop = Shop::first();            //or $shop = Shop::find(1);
    
    foreach($shop->products as $product) {
      $event = Event::create([]);
      $service = Service::create([]);
    
      $product->productable()->saveMany([
        $event, $service
      ]);
    }
    

    Let me know in the comments below if something doesn't work :)

    -- Edit

    First of all, please understand that you can not add an entry to productable_id or productable_type from a hasMany() relation. You need to make sure you are using a morph relation for such purposes.

    Secondly, since you are trying to add products first and not events first, the insertion method is not working out for you. Please note that you must try to create an Event or Service first and then try to associate with a shop.

    The simplest approach to doing it would be

    $shop = Shop::first();
    
    $event = Event::create(['title' => 'Some Event']);
    $event->product()->create(['shop_id' => $shop->id]);
    
    $service = Service::create(['title' => 'Some Service']);
    $service->product()->create(['shop_id' => $shop->id]);
    

    You can also, try to follow my first approach, but the one I just mentioned is definitely supposed to work... and actually that is how it is meant to be inserted/created.

    0 讨论(0)
提交回复
热议问题