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?
One-to-many (Polymorphic) When a single model belongs to more than one type of model on a single association is known as one-to-one polymorphic relationship. For example, if we have three tables, posts, users, and photo table, where photo table represents the polymorphic relation with the users and posts table.
has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With