Laravel 5.4返回错误的最后插入的id

时间:2017-07-25 06:43:12

标签: sql-server-2014 laravel-5.4

我正在使用SQL SERVER 2014和Laravel 5.4我有一个名为tblMyUser的主键MyUserId 现在我想在表中插入一行并获取Last Insered Id但是这会返回关于sql server tblMyUser表的错误id 这是我的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 个答案:

答案 0 :(得分:0)

在laravel 5.4中你可以通过双向获取

  1. 使用insertGetId方法。 link

    file://
  2. 使用getPdo()方法。

    $lastID = DB::table('table_name')->insertGetId(['field_name'=>$field_vale]);
       echo $lastID;