doudou20080720 2018-01-18 15:47
浏览 244
已采纳

如何在Laravel DB :: insert中返回我的OUTPUT子句

I am using Laravel and sqlsrv, connected to SQL Server 2016 and all is working great until I try to use an output clause in my insert query.

Query is something like

INSERT INTO TABLE(Columns) OUTPUT INSERTED.MyDesiredReturnColumn VALUES(Value)

This is working perfectly in SQL Server, and returning the desired value, but using Laravel's DB::insert functionality it is only returning a 1 (for successful insert)

I have a workaround that I would rather not have right now, using the CreatedOn field to return the most recently created row, but this has potential issues.

UPDATES: The field I am attempting to retrieve is a uniqueidentifier field (guid) that is created in SQL, not from Laravel-side

After attempting @PrathameshPalav's recommendation of using the Eloquent model creation, the values are being inserted correctly into the DB, but it is not returning the uniqueidentifier still.

$inserted = MyModel::create($information);
print "inserted id is " . $inserted->MyModelId;

This is printing "inserted id is "

Here is my model:

namespace App;
use Illuminate\Database\Eloquent\Model;    
class MyModel extends Model
{
    //
    protected $table = 'MyModelBase';
    protected $primaryKey = 'MyModelId';
    public $incrementing = false;
    protected $keyType = "string";
    public $timestamps = false;
    protected $fillable = ['field1', 'field2', 'etc'];
}

Any ideas would be greatly helpful.

  • 写回答

3条回答 默认 最新

  • doudu22272099831 2018-01-18 18:07
    关注

    The way that I solved this was by incorporating an Eloquent model (as pointed out by @PrathameshPalav), then (loosely) following this tutorial https://danielkoch.work/log/laravels-eloquent-guids.html

    Specifically this part

    public static function boot() {
        parent::boot();
    
        // Hook when a model is created
        static::creating(function ($model) {
            // Select a new ID
            $result = DB::select( DB::raw('Select NewID() NewUUID') );
    
            $model->{$model->getKeyName()} = $result[0]->NewUUID;
        });
    }
    

    After that, I added the primary key I had defined to the $fillable array and tested, and it works =)

    Thank you both for your help!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?