laravel - 如何在 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();
我怎样才能做到这一点 ?
解决方案
first()
laravel 查询生成器上的函数返回一个stdClass
含义Standard Class。
phpupdate()
中没有调用函数。stdClass
您调用update()
了 stdClass,这会导致错误。
有几种方法可以实现您的目标。
- 使用 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
]);
}
- 如果您不想获取卡数据,请不要调用
first()
$resultQuery = DB::table('cards')->where('api_id', $card->id);
if (your_condition) {
$resultQuery
->update([
'price_usd' => $card->prices->usd
]);
}
- 使用 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,
]);
}
推荐阅读
- r - 运行闪亮的应用程序时如何仅运行特定的mac地址
- php - 使用没有图像名称的父目录在 html 页面上显示图像
- r - ggplot2 - 如何替换图例中的几何符号?
- javascript - 在谷歌网络应用脚本中使用three.js - 无法使用脚本模块类型加载three.js
- reactjs - React - 当浏览器开始绘制或重新绘制哪个生命周期方法结束时?
- java - 请高中需要帮助;将输出写入文件(使用距离程序)?
- ios - App Store Connect 操作错误:密钥 com.apple.developer.healthkit.access 的 ITMS-90164 []
- html - 如何使按钮中的字体真棒图标可点击?
- java - LibGDX - 只有一半的屏幕是活动的游乐场
- numpy - 在 numpy 中,分别将 N 个百分位数应用于 N x M 数组