我有网站购物车的
MySQL表:
Cart: id | user Cart_goods: cart_id | good_id | good_type Details: id | name Appliances: id | name
班车,其中包含商品:
class Cart extends Model { protected $table = 'cart'; protected $fillable = ['user','sum','profit','discount']; protected $guarded = ['user']; public function goods() { return $this->hasMany('App\Models\Good'); } }
Class Good,可以是Detail或Appliance,相对于cart的cart_id:
class Good extends Model { protected $table = 'cart_goods'; protected $types = [ 'Detail' => 'App\Models\Detail','Appliance' => 'App\Models\Appliance' ]; public $primaryKey = 'cart_id'; public function good() { return $this->morphTo(); } }
详细类:
class Detail extends Model { use SoftDeletes; protected $morphClass = 'Detail'; protected $table = 'details'; protected $fillable = ['article','name','photo','price_procurement','price_retail','serial','location_id','type_id','appliance_id','comment','for']; protected $dates = ['deleted_at']; protected $guarded = []; public function goods() { return $this->morphMany('App\Models\Good','good'); } }
我需要把所有的电器和细节放在购物车里.如何使用ORM?
使用
nested eager loading.假设关系方法名称是cartGoods,详细信息和设备,详细信息是购物车的详细信息,并且您已经定义了关系权限:
Card::where('id',$id) ->with('cartGoods.appliances','details') ->first();