【问题标题】:Laravel, How to get product name from product table if the product id stored into CartLaravel,如果产品ID存储在购物车中,如何从产品表中获取产品名称
【发布时间】:2019-07-17 22:05:03
【问题描述】:

我正在使用名为 Gloudemans\Shoppingcart 的购物车; (更多关于购物车:https://github.com/Crinsane/LaravelShoppingcart),在购物车内我存储了许多变量,其中一个是产品表中的 id,我使用购物车在 Blade 视图中显示存储在购物车中的项目,我想要而不是显示产品 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,
 ]

【问题讨论】:

  • 请在您的购物车中发布内容和产品型号。

标签: php laravel


【解决方案1】:

来自文档:

因为能够直接访问一个 来自 CartItem 的模型是否可以将模型与 购物车中的物品。假设您的产品中有一个产品模型 应用。使用 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-liner
Cart::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.';
}

【讨论】:

  • 我该怎么做?
  • 我编辑了帖子,但都在他们的文档中。
【解决方案2】:

这在文档中很清楚。

点击链接https://github.com/Crinsane/LaravelShoppingcart#example

只在控制器中使用

 $cartContents=Cart::Content();

在刀片中

@foreach($cartContents as $row)

            <tr>
                <td>
                    <p><strong>{{$row->name }}</strong></p>
                </td>
            </tr>
@endforeach

【讨论】:

  • 通过购物车添加产品::add('293ad', 'Product 1', 1, 9.99, ['size' => 'large']);第二个参数是名称
  • 我知道,但我不打算将产品名称添加到购物车中!
  • 您可以在添加到购物车时保存产品型号中的名称,例如 $p=Product::find($id);Cart::add('293ad', $p->name, 1 , 9.99, ['size' => '大']);
猜你喜欢
  • 1970-01-01
  • 2017-01-03
  • 2015-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多