Return json with data from three tables in Laravel

//CartController
$itens = CartItem::where('id_cart', $cart->id)->with('product')->get();
return response()->json($itens);

This code returns JSON with the data of the cart item and relative product. But I also want to return the images of the product that is in the ProductImages table .

In my CartItem.php model I have

 public function product(){
    return $this->belongsTo('App\Product', 'id_product');
}

In my Product.php model , I have

  public function images(){
    return $this->hasMany('App\ProductImages', 'id_product');
}

But if I do

 $itens = CartItem::where('id_cart', $carrinho->id)->with('product')->with('image')->get();

I get an error

Calling an undefined relationship [image] on the model [App \ CartItem]

+4
source share
4 answers

You can try:

CartItem::where('id_cart', $carrinho->id)->with('product.images')->get();

, "".

Docs

+6

, with():

CartItem::where('id_cart', $cart->id)
        ->with('product', 'product.images')
        ->get();

(. " " ).

+2

:

$books = App\Book::with('author.contacts')->get();

https://laravel.com/docs/5.3/eloquent-relationships#eager-loading

+2

$itens = CartItem::where('id_cart', $carrinho->id)->with('product','images')->get();

0

Source: https://habr.com/ru/post/1664332/


All Articles