【问题标题】:Can't update table in Laravel 5.4 using Elequent query无法使用 Eloquent 查询更新 Laravel 5.4 中的表
【发布时间】:2017-02-19 18:16:10
【问题描述】:

我正在使用 Laravel 5.4。我为两个(插入和更新)做了一个函数。 当没有找到 id 时,它会点击插入,否则它会点击更新方法。 一切正常,但更新 elequent 查询没有更新表。方法是针对angularjs的http.post方法

控制器功能:

public function postUserJson(Request $req)
{
    //return "check". $req->input('id');

   if ($req->input('id')=='') {
        $user = new User();
        $user->UserName = $req->input('username');
        $user->Password = $req->input('password');

        $user->save();
       return "inserted";
   } else {
       $check= User::find($req->input('id'));

      // $check->ID = $req->input('id');
       $check->UserName = $req->input('username');
       $check->Password = $req->input('password');

       $check->save();
       return "updated".$check;
    }
}

此 (return "updated".$check;) 代码在控制台中返回:

 updated{"ID":13,"UserName":"sadek","Password":"456"}

以前的用户名很伤心。编辑后,我在 save() 方法后用 sadek 获得了编辑后的名称。但是当我刷新它显示悲伤

如何更新表格?

【问题讨论】:

  • 您的模型是否有正确的可填写字段?
  • <?php namespace App; use Illuminate\Database\Eloquent\Model; class User extends Model { // }
  • 可填充字段在模型中并显示为数组...示例:protected $fillable = ['user_id', 'name', 'gender', 'phone', 'email'];

标签: php angularjs laravel-5


【解决方案1】:

您正在以 json 格式发送数据。您的查询字符串不一样。见

"UserName" != username

Password != password

确保这一点。

【讨论】:

    【解决方案2】:

    Eloquent 提供了一种处理上述所有逻辑的方法,称为updateOrCreate()

    来自文档:

    您也可能会遇到想要更新现有模型或创建新模型(如果不存在)的情况。 Laravel 提供了一个 updateOrCreate 方法来一步完成。与firstOrCreate 方法一样,updateOrCreate 持久化模型,因此无需调用save()

    $flight = App\Flight::updateOrCreate(
        ['departure' => 'Oakland', 'destination' => 'San Diego'],
        ['price' => 99]
    );
    

    【讨论】:

      猜你喜欢
      • 2017-10-07
      • 1970-01-01
      • 2018-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-17
      • 2018-09-21
      • 2018-01-11
      相关资源
      最近更新 更多