【问题标题】:Laravel 5.4 return wrong last inserted idLaravel 5.4 返回错误的最后插入 id
【发布时间】:2017-07-25 17:18:02
【问题描述】:

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

    }

【问题讨论】:

  • 试试$myUserId = DB::table('tblMyUser')-&gt;insertGetId(array( 'Name' =&gt; $params['Name'], 'DOB' =&gt; $params['DOB'], 'CustUserId' =&gt; $params['CustUserId'], 'CreatedBy' =&gt; $params['CreatedBy'], 'UpdatedBy' =&gt; $params['UpdatedBy'] ));看看它是否会返回正确的!!

标签: sql-server-2014 laravel-5.4


【解决方案1】:

在 laravel 5.4 中你可以通过 2 方式获取它

  1. 通过使用 insertGetId 方法。 link

    $lastID = DB::table('table_name')->insertGetId(['field_name'=>$field_vale]);
       echo $lastID;
    
  2. 通过使用 getPdo() 方法。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 2011-11-06
    • 2014-09-06
    • 1970-01-01
    • 1970-01-01
    • 2017-07-13
    • 1970-01-01
    相关资源
    最近更新 更多