I've got MySQL tables for site cart:
Cart:
id | user
Cart_goods:
cart_id | good_id | good_type
Details:
id | name
Appliances:
id | name
Class Cart, which contains goods:
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, which can be Detail or Appliance and relative to 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();
}
}
Detail class:
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');
}
}
And i need to get all appliances and details in cart. How can i do it by using ORM?
Use nested eager loading . Assuming that relationship method names are cartGoods
, details
and appliances
, that details
are details of a cart and that you've defined the relationships right:
Card::where('id', $id)
->with('cartGoods.appliances', 'details')
->first();
Try this:
Method 1: If you have a $cart model instance
$cart->load('goods.good');
Method 2: If you need all appliances and details from cart by card ID
Cart::where('id', $cartId)->with('goods.good')->first();
I've done this, problem was in model name, i was writing it to DB like Detail and Appliance, but i was need to use
Relation::morphMap([
'detail' => 'App\Models\Detail',
'appliance' => 'App\Models\Appliance',
]);
In AppServiceProvider class.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.