Laravel 5.4返回错误的最后插入的ID [英] Laravel 5.4 return wrong last inserted id

查看:133
本文介绍了Laravel 5.4返回错误的最后插入的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用SQL SERVER 2014和Laravel 5.4,我有一个名为tblMyUser的表,其主键MyUserId 现在,我想在表中插入一行并获取上次插入的ID,但这相对于sql server tblMyUser表返回错误的ID 这是我的模型MyUser.php

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
        } 

    }

推荐答案

在laravel 5.4中,您可以通过两种方式获取它

  1. 通过使用insertGetId方法. 链接

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

  • 通过使用getPdo()方法.

  • By using getPdo() method.

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

  • 这篇关于Laravel 5.4返回错误的最后插入的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆