Laravel 5.3中的模型关系

时间:2017-02-03 09:10:59

标签: php mysql laravel laravel-5

我有网站购物车的MySQL表格:

Cart:
id | user 

Cart_goods:
cart_id | good_id | good_type

Details:
id | name

Appliances:

id | name

Class Cart,包含商品:

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,可以是详细信息或设备,相对于cart by 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做到这一点?

3 个答案:

答案 0 :(得分:2)

使用nested eager loading。假设关系方法名称为cartGoodsdetailsappliances,则details是购物车的详细信息,并且您已正确定义关系:

Card::where('id', $id)
    ->with('cartGoods.appliances', 'details')
    ->first();

答案 1 :(得分:2)

试试这个:

方法1:如果您有$ cart模型实例

$cart->load('goods.good');

方法2:如果您需要购物车中的所有设备和详细信息,请参阅卡ID

Cart::where('id', $cartId)->with('goods.good')->first();

答案 2 :(得分:1)

我已经完成了这个,问题出在模型名称中,我将它写入数据库,如Detail和Appliance,但我需要使用

Relation::morphMap([
   'detail' => 'App\Models\Detail',
   'appliance' => 'App\Models\Appliance',
]);

在AppServiceProvider类中。