【问题标题】:Laravel Model create not returning primary key on MS SQLLaravel 模型在 MS SQL 上创建不返回主键
【发布时间】:2021-03-17 16:44:06
【问题描述】:

我有模型帐户,它使用第三方 MS SQL 数据库。 我可以创建、更新和删除帐户,但在Account::create(['loginuser' =>'jdoe','loginpwd' => 'supersecret']) 之后,属性“rowguid”为空。 rowguid 是唯一标识符列。

Account::find('28B7F554-9689-4DFD-9C29-1CDAC6513436') 有效。 但我需要创建后的rowguid,将其作为属性存储在另一个模型中。

所以我尝试手动“创建”


$conn = DB::connection('sqlsrv')->getPdo();
$sqlString = "DECLARE @lastinsertid TABLE (rowguid uniqueidentifier);INSERT INTO dbo.accounts (loginuser,loginpwd) OUTPUT INSERTED.rowguid INTO @lastinsertid VALUES (?,?);SELECT rowguid FROM @lastinsertid;";
$sqlVals = ['jdoe','supersecret'];
$stmt = $conn->prepare($sqlString);
$stmt->execute($sqlVals);
$temp = $stmt->fetch(PDO::FETCH_ASSOC);

这会导致:

PDOException with message 'SQLSTATE[42000]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]从字符串转换为唯一标识符时转换失败。'

在 SQL Studio 上运行它并返回 rowguid:

DECLARE @lastinsertid TABLE (rowguid uniqueidentifier);
INSERT INTO accounts (loginuser,loginpwd) OUTPUT INSERTED.rowguid INTO @lastinsertid VALUES ('johndoe','supersecret');
SELECT rowguid FROM @lastinsertid;

我在带有 msodbcsql17-17.7.2.1-1 的 Linux 上使用 Laravel 8.32.1 和 PHP 8.0.3

【问题讨论】:

  • 使用这里展示的 Trait 会起作用吗? laracasts.com/discuss/channels/eloquent/…
  • 尝试使用 lastInsertId() 方法 $lastId = DB::getPdo()->lastInsertId();
  • @hppycoder thx,Trait 确实有效!
  • @PatrickHeppler 很高兴听到这个消息!我将此作为正式答案,以帮助遇到 StackOverflow 的其他人寻找相同的东西。我不确定 Tippin 是否在这里(我想他们是),但我很欣赏他们所做的工作。

标签: php sql-server laravel eloquent


【解决方案1】:

将其移至正式答案,因为laracasts - Using uuid for the id and getting it returned after Create or Save 上的链接可能会更改,并且答案是通过 cmets 找到的。

Tippin 展示了如何使用以下 Trait,因为 Laravel 将 Ramsey 包合并到 Str::class 外观中。这是为了解决 UUID + SQL Server 的问题。

<?php

namespace App\Traits;

use Illuminate\Database\Eloquent\Model;
use Str;

trait Uuids
{
    /**
     * On model creating, set the primary key to UUID
     */
    public static function bootUuids()
    {
        static::creating(function (Model $model) {
            $model->{$model->getKeyName()} = Str::orderedUuid()->toString();
        });
    }
}

示例用法:

$test = User::create([
    'first' => 'Derpy',
    'last' => 'Herpy',
    'slug' => '12345',
    'active' => 1,
    'email' => 'ok@ok.com',
    'password' => 'password'
]);

dump($test->id);

//"91e85023-4508-4c90-972b-5298e1768702"

$test2 = new User();
$test2->first = 'nope';
$test2->last = 'never';
$test2->slug = '8888';
$test2->active = 1;
$test2->email = 'whyr@lolol.com';
$test2->password = '987987987';
$test2->save();

dump($test2->id);

//"91e85023-55a7-46e0-801c-8fa9ed9a846a"

【讨论】:

    猜你喜欢
    • 2018-01-06
    • 2016-09-08
    • 1970-01-01
    • 2016-03-31
    • 2016-07-07
    • 2019-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多