首页 > 解决方案 > 如何在 if 语句中使用 laravel db query ->update() 方法

问题描述

我想检查一下是否,如果该条件为真,我想更新之前获取的记录。

$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

解决方案


first()laravel 查询生成器上的函数返回一个stdClass含义Standard Class

phpupdate()中没有调用函数。stdClass您调用update()了 stdClass,这会导致错误。

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

  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,
    ]);
}

推荐阅读