且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Laravel变形关系

更新时间:2023-12-04 07:53:46

首先从Product 模型

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 :)

首先,请理解您不能从hasMany()关系向productable_idproductable_type添加条目.您需要确保为此目的使用morph关系.

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.

最简单的方法是

$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.