【问题标题】:How can I use laravel db query ->update() method in if statement如何在 if 语句中使用 laravel db query ->update() 方法
【发布时间】:2019-12-19 06:38:29
【问题描述】:

我想检查 if 中的某些内容,如果该条件为真,我想更新之前获取的记录。

$resultQuery = DB::table('cards')->where('api_id', $card->id)->first();

if (this condition will pass I want to update this record) {
    $resultQuery->update(array('price_usd' => $card->prices->usd));
}

当我像这样使用 ->update() 时,出现错误:

调用未定义的方法 stdClass::update();

我该怎么做?

【问题讨论】:

    标签: laravel


    【解决方案1】:

    laravel 查询构建器上的first() 函数返回一个stdClass,意思是标准类

    在 php 中的 stdClass 中没有名为 update() 的函数。您在 stdClass 上调用了update(),这会导致错误。

    有几种方法可以实现您的目标。

    1. 使用 Laravel 查询生成器 update() 函数。
    $resultQuery = DB::table('cards')->where('api_id', $card->id)->first();
    
    if (your_condition) {
        Db::table('cards')
            ->where('api_id', $card->id)
            ->update([
                'price_usd' => $card->prices->usd
            ]);
    }
    
    1. 如果不想取卡数据,请不要拨打first()
    $resultQuery = DB::table('cards')->where('api_id', $card->id);
    
    if (your_condition) {
        $resultQuery
            ->update([
                 'price_usd' => $card->prices->usd
            ]);
    }
    
    1. 使用 Eloquent 模型(Laravel 的首选方式)

    为卡片创建一个 Eloquent 模型(如果你还没有这样做的话)。

    public class Card extends Model
    {
    
    }
    

    使用 eloquent 查询构建器来获取数据。并使用模型update()函数更新数据。

    $resultingCard = Card::where('api_id', $card->id)->first();
    
    if (your_condition) {
        $resultingCard->update([
            'price_usd' => $card->prices->usd,
        ]);
    }
    

    【讨论】:

      【解决方案2】:

      如果你使用的是模型

      您可以添加卡片控制器

      $card = Card::where('api_id', $card->id)->first();
      
      if (someConditional) 
      {
        // Use card properties, number is a example.
        $card->number = 10
        // This line update this card.
        $card->save();
      }
      

      您可以了解更多关于eloquent here的信息。

      【讨论】:

        【解决方案3】:

        类似这样的:

        $resultQuery = DB::table('cards')->where('api_id', $card->id);
        
        if ($resultQuery->count()) {
        
          $object = $resultQuery->first();
          $object->price_usd = $card->prices->usd;
          $object->save();
        }
        

        或在此处寻找替代解决方案:Eloquent ->first() if ->exists()

        【讨论】:

        • 他没有提到他的情况,可能不是关于结果的。除此之外,您的答案几乎是正确的。
        猜你喜欢
        • 1970-01-01
        • 2016-06-12
        • 2010-11-12
        • 1970-01-01
        • 1970-01-01
        • 2022-06-22
        • 2011-12-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多