问题
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
By using insertGetId method. link
$lastID = DB::table('table_name')->insertGetId(['field_name'=>$field_vale]); echo $lastID;
By using getPdo() method.
$lastID = DB::getPdo()->lastInsertId(); echo $lastID;
来源:https://stackoverflow.com/questions/45295738/laravel-5-4-return-wrong-last-inserted-id