首页 文章

Laravel变形关系

提问于
浏览
2

我有一个关于在Laravel中保存多态关系的问题 . 这是我想在laravel中创建的模型 .

Class diagram

商店有许多产品,产品可以是“项目”,“活动”或“服务” .

我有以下表格:

  • 商店

  • id

  • user_id

  • 名字

  • 事件

  • id

  • 公众

  • Headers

  • 说明

  • 产品

  • id

  • shop_id

  • productable_id

  • productable_type

这就是我设置模型的方式:

class Shop extends Model{
    public function products(){
        return $this->hasMany('App\Product');
    }
}

class Product extends Model{
    public function productable(){
        return $this->morphTo();   
    }
}

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

我希望能够做到以下几点:

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

但它不起作用!当我试图保存我得到的关系时:

Illuminate\Database\QueryException with message 'SQLSTATE[HY000]: General error: 1 no such column: shop_id (SQL: update "accendo_events" set "updated_at" = 2016-11-26 10:11:02, "shop_id" = 1 where "id" = 1)'

任何人都知道这出错的地方?我可能误解了这种关系......

1 回答

  • 5

    首先从 Product Model 添加 Shop 的后退关系

    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');
      }
    }
    

    现在,我不确定你为什么要尝试制作一个空的事件并将其添加到所有产品中,但是如果你想为任何用例做这件事......请按照以下方法进行... :)

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

    如果有什么不起作用,请在下面的评论中告诉我:)

    - 编辑

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

    其次,由于您首先尝试添加产品而不是事先添加事件,因此插入方法不适合您 . 请注意,您必须尝试创建 Event or Service first ,然后尝试与商店关联 .

    这样做最简单的方法是

    $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]);
    

    您也可以尝试按照我的第一种方法,但我刚才提到的那个肯定应该工作......实际上这就是它的插入/创建方式 .

相关问题