如果新价格更低,Laravel会雄辩地更新记录

如果新价格更低,Laravel会雄辩地更新记录,laravel,eloquent,model,Laravel,Eloquent,Model,我肯定我在这里遗漏了一些简单的东西,但我能找到的所有例子似乎都不起作用 简言之,表中有“报价”的价格。如果没有带有参数的价格,请创建一个记录(此部件正在工作),如果没有,请检查新价格是否便宜,如果便宜,则更新记录 这是我的密码: $priceExist = OfferPrice:: where('offer_id', $offer_id, 'AND') ->where('personal', $price['personal'], 'AND') ->wher

我肯定我在这里遗漏了一些简单的东西,但我能找到的所有例子似乎都不起作用

简言之,表中有“报价”的价格。如果没有带有参数的价格,请创建一个记录(此部件正在工作),如果没有,请检查新价格是否便宜,如果便宜,则更新记录

这是我的密码:

$priceExist = OfferPrice:: 
    where('offer_id', $offer_id, 'AND')
    ->where('personal', $price['personal'], 'AND')
    ->where('status', 1, 'AND')
    ->where('deposit', $price['deposit'], 'AND')
    ->where('duration', $price['duration'], 'AND')
    ->where('mileage', $price['mileage'])->get()->first();

if (!$priceExist) {
    $offerPrice = new OfferPrice($price);
    $offerPrice->save();
} else if ( $price['price'] < $priceExist->price) {
    $priceExist->price = $price['price'];
    $priceExist->save();
}

我认为您应该直接使用
->first()
而不是
->get()->first()

这种类型的错误表明您正在尝试使用数组/对象访问数组


虽然问题中没有足够的信息给出具体的答案,但我怀疑
$price['price']
的内容与您想象的不一样。这可能值得倾销
$price

谢谢您的回复,但这也有同样的错误。我添加了第二个示例,其中价格按预期更新,确认价格已设置。谢谢没问题,但我很困惑这是两件不同的事?在第一个示例中,$price来自何处?price是从控制器传递的数组。在这两个示例中,结构是相同的,我只是复制了对OfferPrice的调用,并直接调用了update。谢谢你的帮助:)
$priceExist = OfferPrice::
    where('offer_id', $offer_id, 'AND')
    ->where('personal', $price['personal'], 'AND')
    ->where('status', 1, 'AND')
    ->where('deposit', $price['deposit'], 'AND')
    ->where('duration', $price['duration'], 'AND')
    ->where('mileage', $price['mileage'])->get()->first();

if (!$priceExist) {
    $offerPrice = new OfferPrice($price);
    $offerPrice->save();
} else if ( $price['price'] < $priceExist->price) {
    OfferPrice::
    where('offer_id', $offer_id, 'AND')
    ->where('personal', $price['personal'], 'AND')
    ->where('status', 1, 'AND')
    ->where('deposit', $price['deposit'], 'AND')
    ->where('duration', $price['duration'], 'AND')
    ->where('mileage', $price['mileage'])
    ->update(['price' => $price['price']]);
}