【问题标题】:AJAX sends data to controller, how do I update the correct id?AJAX 向控制器发送数据,如何更新正确的 id?
【发布时间】:2017-05-02 11:24:08
【问题描述】:

我正在使用 ajax 将数据发布到控制器,我需要根据我传递的 id 更新记录。我将如何使用 Laravel Eloquent 来解决这个问题?这是控制器...我知道数据正在正确地传递给控制器​​,只是不知道如何根据我发送的 id 进行更新。感谢您的帮助。

public function home(Request $request) {

$updateCus = New Customer($request->all());
$updateCus->update()->where('id', $request['id']);

}

【问题讨论】:

  • 提及您要更新的列

标签: php ajax laravel eloquent


【解决方案1】:

正确的语法是:

Customer::where('id', $request->id)->update([
    'name' => $request->name,
    'country' => $request->country,
]);

或者,如果您想更新许多列:

Customer::where('id', $request->id)->update($request->all());

【讨论】:

  • 要补充这一点,请注意模型的 $guarded$fillable 属性,这可能会阻止您更新批量分配中的某些字段。
【解决方案2】:

如果你想更新一条记录,你必须先从数据库中获取它。相反,您正在创建一个新客户。你应该这样做:

public function home(Request $request) {
    $customer = Customer::where('id', $request['id'])->first();
    if ($customer) {
        $customer->field1 = $request['field1'];
        //... update the fields you want to
        $customer->save();
    } else {
        //user not found...
    }
}

【讨论】:

    【解决方案3】:
    public function home(Request $request){
    $id=$request->id;
    $update=\DB:"table('tablename')->update(['columnname'=>$columname])->where('id',$id);
    }
    

    【讨论】:

    • 通常建议您围绕代码添加更多上下文/解释(而不是仅提供代码答案),因为这会使答案更有用。
    • 虽然这段代码 sn-p 可以解决问题,但它没有解释为什么或如何回答这个问题。请include an explanation for your code,因为这确实有助于提高您的帖子质量。请记住,您正在为将来的读者回答问题,而这些人可能不知道您的代码建议的原因。 举报者/评论者: For code-only answers such as this one, downvote, don't delete!
    猜你喜欢
    • 2017-02-19
    • 2023-03-20
    • 1970-01-01
    • 2018-12-22
    • 1970-01-01
    • 2014-04-26
    • 2015-04-16
    • 1970-01-01
    相关资源
    最近更新 更多