簡體   English   中英

Laravel,如果將商品ID存儲到購物車中,如何從商品表中獲取商品名稱

[英]Laravel, How to get product name from product table if the product id stored into Cart

我正在使用名為Gloudemans \\ Shoppingcart的購物車; (有關購物車的更多信息,請訪問: https : //github.com/Crinsane/LaravelShoppingcart ),在購物車內部,我存儲了許多變量,其中之一是產品表中的ID,我使用購物車在Blade視圖中顯示了存儲在購物車中的商品,我想要顯示商品名稱而不是顯示產品ID,但不能在購物車中使用leftjoin,因為它說方法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,
 ]

這在文檔中很清楚。

跟隨鏈接https://github.com/Crinsane/LaravelShoppingcart#example

只需在控制器中使用

 $cartContents=Cart::Content();

刀片式

@foreach($cartContents as $row)

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

從文檔中:

因為能夠從CartItem直接訪問模型非常方便,所以可以將模型與購物車中的項目相關聯。 假設您的應用程序中有一個產品模型。 使用associate()方法,您可以告訴購物車該購物車中的某個商品與產品模型相關聯。

這樣,您就可以直接從CartItem訪問模型!

可以通過CartItem上的model屬性訪問模型。

如果您的模型實現了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.';
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM