使用数据透视表LARAVEL

时间:2019-07-25 19:11:17

标签: php laravel eloquent

我在LARAVEL API上有一个小问题。如何获取数据透视表的数据并在其他控制器中使用它?我有3个表,库存,产品和库存产品。最后一张表格包含(产品的库存和价格数据,因为它们取决于库存而有所不同),我想使用该价格和库存值(来自数据透视表)

在添加库存和数据透视表之前,价格和库存是直接分配给每种产品的值,并且在我拥有的购物车控制器中,我像这样直接使用它们,并且效果很好,但是现在来自一个表的值我不知道如何检查它们。

首先,我需要在资源中调用价格值

CartItemResource: 此资源用于显示购物车中的一系列产品

$product = Product::find($this->product_id);

    return [
        'productID' => $this->product_id,
        'inventoryID' => $this->inventory_id,
        'name' => $product->name,
        'Quantity' => $this->quantity,
        'price' =>  $product->pivot->price// this should show the price of the relation between product_id and inventory_id on my pivot table
    ];

正在返回: 试图获取非对象的属性“价格”

并且应该返回类似的内容:

//if I add to the cart these two products
{
    "Items in Cart": [
        {
            "productID": 1,
            "inventoryID": 1,
            "name": "Product",
            "Quantity": 3,
            "price", 10
        }
{
            "productID": 2, 
            "inventoryID": 2,
            "name": "Product 2",
            "Quantity": 1,
            "price", 20
        }
    ]
}

之后,我需要能够使用该数据进行结帐

曾经有价格和库存直接分配给产品(没有数据透视表或库存)但无法正常工作的情况,

CartController:

 $items = $cart->items;

 foreach ($items as $item) {

            $product = Product::find($item->product_id);
            $price = $product->price;//it used to work before
            $inStock = $product->stock;//it used to work before


            if ($inStock >= $item->quantity) {

                $TotalPrice = $TotalPrice + ($price * $item->quantity);

                $product->stock = $product->stock - $item->quantity;
                $product->save();
            } else {
                return (only ' . $inStock . ' units are in stock)
            } }

在我的产品模型中:

    public function inventories()
    {       
         return $this->belongsToMany('App\Inventory','inventory_product','product_id','inventory_id')->withPivot(['price','stock'])->withTimestamps();     
    }

在我的库存模型中:

class Inventory extends Model
{   
    public function products()
    {  
       return $this->belongsToMany('App\Product','inventory_product','inventory_id','product_id')->withPivot(['price','stock'])->withTimestamps();        
    }
}

还有我的stock_product迁移表:

$table->increments('id');
    $table->integer('inventory_id')->unsigned();
    $table->integer('product_id')->unsigned();
    $table ->integer('price');
    $table ->integer('stock');
    $table->timestamps();
    $table-> foreign('inventory_id')->references('id')->on('inventories')->onDelete('cascade');
    $table-> foreign('product_id')->references('id')->on('products')->onDelete('cascade');

预先感谢您:)

0 个答案:

没有答案