Laravel 更新语法 - 用数组更新记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13685593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:21:16  来源:igfitidea点击:

Laravel Update Syntax - Updating Record with Array

postlaravellaravel-routing

提问by jamis0n

I'm having trouble doing a basic record update via POST in Laravel.

我在 Laravel 中通过 POST 进行基本记录更新时遇到问题。

I have captured all the post data in an array, and if the existing Order# is 0, then I create a new record (works fine). Otherwise I update the existing record.

我已经在一个数组中捕获了所有发布数据,如果现有的 Order# 为 0,那么我创建一个新记录(工作正常)。否则我更新现有记录。

Order.php

订单.php

class Order extends Eloquent {
    public static $table = 'my_orders';
}

Routes.php

路由.php

//Handle a new order POST
Route::post('order', array('do' => function() {
    $thisOrder = array(
         'qty' => Input::get('quantity'),
         'desc' => Input::get('description'),
    );

    $thisOrderID = Input::get('orderNo');

    //CHECK FOR NEW OR EXISTING ORDER
    if($thisOrderID > 0) {
        //THIS FUNCTION SOMEHOW RETURNS THE FUNCTION CALL AND DOESNT CONTINUE PAST
        //AND THE RECORD IS NOT UPDATED
        $updateOrder = Order::update($thisOrderID, $thisOrder);
    }
}

Update: The code above does in fact work. I had a validation error, which was causing the function to return early.

更新:上面的代码确实有效。我有一个验证错误,导致函数提前返回。

回答by markvaneijk

Instead of this line:

而不是这一行:

$updateOrder = Order::update($thisOrderID, $thisOrder);

You need to do:

你需要做:

$updateOrder = Order::find($thisOrderID)->update($thisOrder);

With find() (which equals where_id()) you select a specific row from the database and with update you pass the new data.

使用 find() (等于 where_id()),您可以从数据库中选择特定行,并使用 update 传递新数据。

回答by ceesvanegmond

What do you think of this:

你觉得这怎么样:

//Handle a new order POST
Route::post('order', array('do' => function() {
    $thisOrder = array(
         'qty' => Input::get('quantity'),
         'desc' => Input::get('description'),
    );

    $thisOrderID = Input::get('orderNo');

    $order = Order::find( $thisOrderID );

    //CHECK FOR NEW OR EXISTING ORDER
    if( $order ) {
        $order->title = 'New order title';
        $order->desc = 'New description';
        $order->save();
    }
}

回答by Knight

erm , I will suggest to do it this way, if $thisOrder include the key, it will just update the record, else it will just create a new record.

erm ,我会建议这样做,如果 $thisOrder 包含密钥,它只会更新记录,否则只会创建一个新记录。

$thisOrder = array(
     'orderNo' => Input::get('orderNo'),
     'qty' => Input::get('quantity'),
     'desc' => Input::get('description'),
);

$updateOrder = Order::save($thisOrder);

if Input::get('orderNo') no value will be create else update

如果 Input::get('orderNo') 没有值将被创建否则更新