Laravel,如果产品 ID 存储在购物车中,如何从产品表中获取产品名称

我使用名为 Gloudemans\Shoppingcart 的购物车;(有关购物车的更多信息:https : //github.com/Crinsane/LaravelShoppingcart),在购物车内我存储了许多变量,其中之一是产品表中的 id,我使用购物车在刀片视图中显示购物车中存储的项目,我不想显示产品 ID 来显示产品名称,但不能在购物车中使用 leftjoin,因为它说 Method leftjoin 不存在。


控制器:


 $cartContents=Cart::Content();

  $products= Product::all();

刀片视图:


   @foreach($cartContents as $cartContent)

  {{$cartContent->id}}  // here I want to show product name not product id

   @endforeach

产品型号:


 protected $table="products";

  protected $fillable=[

  'category_id',    

  'storeinfo_id',

  'product_price',

 'product_name',

 'product_details',

 'product_unitsize',

 'product_unitsizelast',

 'product_unitname',

 'product_unittext',

 'product_unitserve',

 'product_image',

  'show'

    ];

大车:


 Cart::add([


'id' => $request->cartproductid,

'name' =>$request->special,

'qty' => $request->cart_quantity,

'price' => $request->cart_price,

    'name' =>$request->special,


'options' => 


[

'size' =>$request->cart_size,

'storeinfo_id' =>$request->storeinfo_id,

'serve' => $request->cart_serve,

 ]


慕后森
浏览 128回答 2
2回答

慕斯王

从文档:因为能够直接从 CartItem 访问模型非常方便,所以可以将模型与购物车中的项目相关联。假设您的应用程序中有一个 Product 模型。使用 associate() 方法,您可以告诉购物车购物车中的商品与 Product 模型相关联。这样您就可以直接从 CartItem 访问您的模型!可以通过 CartItem 上的模型属性访问模型。如果您的模型实现了 Buyable 接口并且您使用您的模型将商品添加到购物车,它将自动关联。因此,您必须关联购物车中的模型,甚至更好的是,在该模型上实现 Buyable 接口。这是他们文档中的示例:// First we'll add the item to the cart.$cartItem = Cart::add('293ad', 'Product 1', 1, 9.99, ['size' => 'large']);// Next we associate a model with the item.Cart::associate($cartItem->rowId, 'Product');// Or even easier, call the associate method on the CartItem!$cartItem->associate('Product');// You can even make it a one-linerCart::add('293ad', 'Product 1', 1, 9.99, ['size' => 'large'])->associate('Product'); // Now, when iterating over the content of the cart, you can access the model.foreach(Cart::content() as $row) {    echo 'You have ' . $row->qty . ' items of ' . $row->model->name . ' with     description: "' . $row->model->description . '" in your cart.';}
打开App,查看更多内容
随时随地看视频慕课网APP