1

I have very simple 2 tables

1. products (id,name)
2. adjustment (id,product_id,amount)

All tables have foreign keys and models are define as bellow

class Product model have

public function adjustment()
{
 return $this->hasMany(Adjustment::class);
}

and class Adjustment model have

public function product()
{
return $this->belongsTo(Product::class);
}

now I want to have query of adjustment model

Adjustment::with('product')->get();

I got result of Adjustment table but not product table. what is wrong I am doing here?

Mr.SH
  • 397
  • 1
  • 9
  • 27

1 Answers1

0

You are doing the wrong query. You may try this:

$products = Product::with('adjustment')->get();

Then to access the adjustments record. You can do like:

foreach($products as $product){
    foreach($products->adjustment as  $adjustment){
       //do your stuff
    }
}

If you really want to query the adjustments's products. You can do this like:

$product=Adjustment::find(1)->product;

Azahar Alam
  • 708
  • 5
  • 16
  • I want to get adjustment records not Products records , Thanks – Mr.SH Feb 03 '21 at 14:45
  • how? invert can you please explain – Mr.SH Feb 03 '21 at 18:32
  • According to your schema structure: you cant also revert your parent child relation. Sorry for my previous comment. If you read the doc of Eager loading, you can see it reduces the N+1 query problem into just one query. That means if you have 1 Parent row with N child row you can load this N+1 query into 1 query. Thats what i did in my answer. You have products with many adjustments. But for one adjustment you have only one products. Ignore Eager loading. You can simply query the adjustment with its id or using where clause. – Azahar Alam Feb 03 '21 at 18:51
  • You can query the parent model like: Adjustment::find(1)->products; – Azahar Alam Feb 03 '21 at 18:55
  • I have updated my answer. Let me know if this help you out – Azahar Alam Feb 03 '21 at 19:07