【问题标题】:Object of class Illuminate\Support\Collection could not be converted to int php beginnerIlluminate\Support\Collection 类的对象无法转换为 int php 初学者
【发布时间】:2017-10-05 11:26:18
【问题描述】:

请就我的代码如何正常工作给我一些建议。我有一个循环,它为我提供了一个 id 和数量,以便将每个循环更新到我的数据库中。

但是当我将它传递给我的私有函数并尝试执行它时出现错误。 我只是 PHP/Laravel 的初学者。 这是我的完整代码:

public function updateProduct(Request $request) {
    $ids = array();
        foreach ($request->products as $ship_id) {
            $product_id = DB::table('shipping_products')->select('product_id','quantity')
            ->where(['shipping_products.shipping_id'=>$ship_id])
            ->get();
            array_push($ids,$product_id);
        }

        foreach ($ids as $value) {
            foreach ($value as $update) {
                $this->updateProductQty($update->product_id,$update->quantity);
            }
        }
    }

    private function updateProductQty($product_id, $quantity_order) {
        $qty = DB::table('products')->select('quantity')
            ->where(['products.product_id'=>$product_id])
            ->get();
        $updateTotalQty = $qty - $quantity_order;
        DB::table('products')
            ->where('product_id', $product_id)
            ->update(array(           
            'quantity' => $updateTotalQty
        ));

    }

我在这行中有一个错误:

$this->updateProductQty($update->product_id,$update->quantity);

它显示错误消息:

Object of class Illuminate\Support\Collection could not be converted to int

【问题讨论】:

  • productsquantity 的声明类型是什么?我认为productsCollectionType
  • @YaatSuka 感谢您的快速回复。这是 {#300 ▼ +"product_id": 1 +"quantity": 1 } 当 i dd($update) 在 foreach 中时
  • $updateTotalQty 的值是多少?
  • 私有函数 updateProductQty($product_id, $quantity_order) 它是一个函数,我想要的只是每次 foreach 循环获取数据时从数据库更新我的数据
  • 对不起,我在这一行谈到了变量:$updateTotalQty = $qty - $quantity_order;

标签: php laravel sql-update laravel-5.4 private-functions


【解决方案1】:

尝试这样做以检查数据是否是您要查找的数据:

foreach ($ids as $value) {
        foreach ($value as $update) {
            //$this->updateProductQty($update->product_id,$update->quantity);
            var_dump($update);
            var_dump($update->product_id);
            var_dump($update->quantity);
        }
    }

【讨论】:

  • 是的? $update->product_id 给了我我想要的东西以及 $update->quantity。我认为这是因为它们是对象。而我的 $updateTotalQty 是一个整数?
  • object(stdClass)#300 (2) { ["product_id"]=> int(1) ["quantity"]=> int(1) } int(1) int(1) 对象(stdClass)#299 (2) { ["product_id"]=> int(2) ["quantity"]=> int(1) } int(2) int(1) object(stdClass)#298 (2) { ["product_id"]=> int(1) ["quantity"]=> int(1) } int(1) int(1)
  • var_dump($update->product_id); int(1) int(2) int(1) var_dump($update->quantity); int(1) int(1) int(1)
  • 试过了但没有任何反应 // $updateTotalQty = $qty->quantity - $quantity_order;
  • 请把它放在你的私有函数的第一行(在查询之前):var_dump($product_id);die; 并给我结果。我认为一个变量不是您要查找的类型:它可能是数组或整数集合
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-08
  • 1970-01-01
  • 1970-01-01
  • 2019-01-28
  • 2015-09-23
  • 2019-06-27
  • 2019-01-10
相关资源
最近更新 更多