繁体   English   中英

使用Laravel中三个表中的数据返回json

[英]Return json with data from three tables in Laravel

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

此代码返回包含购物车项目数据和相关产品的JSON。 但我也想要返回产品的图像,该图像位于ProductImages表中。

在我的模型CartItem.php中我有

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

在我的模型Product.php中我有

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

但是,如果我这样做

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

我收到了错误

在模型[App \\ CartItem]上调用未定义的关系[images]

您可以尝试:

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

要急切加载嵌套关系,您可以使用“dot”语法。

文件

您应该使用with()加载两个表:

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

您可以在此处阅读说明(请参阅嵌套的预先加载部分)。

你应该使用嵌套的eager load函数:

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

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

就这样使用吧

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM