【发布时间】: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