Why Eloquent only retrieves one row of hasMany relationship?

Viewed 28

I am trying to make an API using Laravel. I have two models: Clients and products. Client model has a one-to-may relationship with Products model (because one client can have many products)

The relation is specified inside the client model:

 public function products() {
    return $this->hasMany(Product::class, 'idProduct');
}

The client controller method to get the client data (and its products) is the following:

 $clients= Client::->where('IS_DELETE', 0)->with('products')->get();

However when I make the request, I only get one product associated to the client (instead all the products)

{
"message": "Clients found",
"clients": [
    {
        "idClient": 10,
        "name": "Ala",
        "productsNumber": 6,
        "IS_DELETE": 0,
        "products": [
            {
                "idProduct": 10,
                "idClient": 9,
                "description": "Some product",
                "price": "12.55",
                "IS_DELETE": 0,
            }
        ]
    },
{
        "idClient": 11,
        "name": "Robert",
        "productsNumber": 8,
        "IS_DELETE": 0,
        "products": [
            {
                "idProduct": 12,
                "idClient": 11,
                "description": "Another product",
                "price": "18.55",
                "IS_DELETE": 0,
            }
        ]
    },

In the response above, we can notice that every client have some amounts of products, but I'm getting only one.

Pls help.

1 Answers

Your query should be like this:

   $clients = Client::where('IS_DELETE', 0)->with('products')->get();

HasMany relation should be like this:

return $this->hasMany(Product::class, 'foreign_key', 'local_key');

Can you check if this fields are correct and run again?

And you do not have to use IS_DELETE. Laravel already support SoftDelete, you can use this trait and add this field to your database migrations. It will automatically set deleted_at column when you try to delete any resource.

Related