Ashish
Ashish

Reputation: 498

Laravel: 2nd level relationship only fetching single row

I am using Laravel 5.6 and I have relation between 3 tables. Cart->cartItem->Images Here is my controller code:

$cart = Cart::where('created_by_id', Auth::user()->id)->with('cartDetails')->first();

Here is my cart model:

public function CartItem()
    {
        return $this->hasMany('App\Http\models\CartItem', 'cart_id')->with('images');
    }

Here is the model of cartItem:

public function images()
    {
        return $this->belongsTo('App\Http\models\ProductImage', 'item_id', 'product_id');
    }

Now in result I am getting only single image even though I have multiple images in the database. It always picking up the last inserted image. I want to get all images or at least the first one but not the last one. Please help.

Upvotes: 0

Views: 39

Answers (2)

Dhruv Raval
Dhruv Raval

Reputation: 1583

if you have multiple images in the database of items then you have to use hasMany() insted of belongsTo().

public function images()
{
    return $this->hasMany('App\Http\models\ProductImage', 'item_id', 'product_id');
}

When use belongTo() ?

suppose you have post and comment model. Now you want post of comment . That is inverse of a hasMany relationship.To define the inverse of a hasMany relationship, define a relationship function on the Comment (child) model which calls the belongsTo method

 public function post()
    {
        return $this->belongsTo('App\Post');
    }

Upvotes: 1

IndianCoding
IndianCoding

Reputation: 2683

You should use hasMany() relation instead of belongsTo():

public function images()
{
    return $this->hasMany('App\Http\models\ProductImage', 'item_id', 'product_id');
}

Upvotes: 2

Related Questions