Home > Software design >  Laravel 'hasMany' relationship not working, no idea why
Laravel 'hasMany' relationship not working, no idea why

Time:07-28

I'm having trouble retrieving data through relationships.

My database structure (simplified):

orders:
   id
   user_id
   product_id

order_items:
   order_id
   product_id

I need to get using relationships, all orders along with the items in the array.

Order model:

public function items()
{
    return $this->hasMany(OrderItem::class, 'order_id', 'id');
}

Test controller:

public function test()
{
    return Order::with('items')->get();
}

Result I got when accessing test():

[
 {
   "id": "d7baaae9-b925-4ff0-8bba-13e8e88d429b",
   "user_id": "fa2a5f73-379d-4ab7-9bc5-81cdbd47f3b0",
   "subtotal": "0.00",
   "discount": "0.00",
   "coupon_code": "0",
   "total": "0.00",
   "paid": false,
   "refunded": false,
   "created_at": "2022-07-26T16:41:50.000000Z",
   "updated_at": "2022-07-26T17:51:45.000000Z",
   "items": [
  
   ]
 }
]

The "items" array does not exist in the orders table, it is coming through the relationship, but it comes empty. There is a record in the database relating orders with order_items, the OrderItem model is correctly accessing the database when I test. I don't know what the problem could be.

[EDIT_01]: I just found out that the problem is in the id I'm using, I'm using type Uuid (Ramsey\Uuid\Uuid\Uuid::uuid4()) for the keys of my tables, somehow it's not working, but when I testo with conventional ID works. Help-me.

CodePudding user response:

hope you found a solution, if not testing out your code sample here, and everything works fine for me,

public function items()
{
    return $this->hasMany(OrderItem::class);
}

use this instead, should give you a better result

CodePudding user response:

Try removing the third parameter and just use this:

return $this->hasMany(OrderItem::class, 'order_id');

This should work given your Database setup example, make sure you actually have items in your database that belong to that order you are debugging as well.

  • Related