Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model relationships in Laravel 5.3

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?

like image 305
Detryer Avatar asked Feb 03 '17 09:02

Detryer


People also ask

What are different types of relationships we can define on models in Laravel?

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.

Does Laravel have relationship?

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.


2 Answers

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();
like image 95
Alexey Mezenin Avatar answered Oct 01 '22 20:10

Alexey Mezenin


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();
like image 21
Paras Avatar answered Oct 01 '22 20:10

Paras