Laravel 5.4 return wrong last inserted id

安稳与你 提交于 2019-12-11 16:58:41

问题


I am using SQL SERVER 2014 and Laravel 5.4 I habe a tble named tblMyUser whose primary key MyUserId Now I want to insert one row in table and get Last Insered Id but this return wrong id with respect to sql server tblMyUser table This is my Model MyUser.php

namespace App;

use DB;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

    class MyUser extends Authenticatable
    {
        use Notifiable;
        protected $table = 'tblMyUser';
        protected $primaryKey = 'MyUserId';
        protected $fillable = ['Name','DOB','CustUserId','CreatedBy','UpdatedBy'];
        public $timestamps = false;

        public static function addUser($params){
             $myUser = MyUser::create(array(
                'Name' => $params['Name'],
                'DOB' => $params['DOB'],
                'CustUserId' => $params['CustUserId'],
                'CreatedBy' => $params['CreatedBy'],
                'UpdatedBy' => $params['UpdatedBy']
            ));
            echo "<pre>";print_r($myUser->MyUserId);exit;
            // Its returning wrong Id which is not in tblMyUser
        } 

    }

回答1:


In laravel 5.4 you can get it by 2 way

  1. By using insertGetId method. link

    $lastID = DB::table('table_name')->insertGetId(['field_name'=>$field_vale]);
       echo $lastID;
    
  2. By using getPdo() method.

    $lastID = DB::getPdo()->lastInsertId();
    echo $lastID;
    


来源:https://stackoverflow.com/questions/45295738/laravel-5-4-return-wrong-last-inserted-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!