如何在MySQL上正确地将Laravel与SQL Server结合使用? [英] How to correctly use Laravel with SQL Server instead on MySQL?

查看:97
本文介绍了如何在MySQL上正确地将Laravel与SQL Server结合使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将SQL Server与我的Laravel项目一起用于我的数据库.我能够将SQL Server与Laravel 5.2连接.但是,当我尝试将数据播种到表中时,会出现此错误

I am trying to use SQL Server for my databases with my Laravel project. I was able to connect SQL Server with Laravel 5.2. However, when I try to seed data into the table I get this error

[Illuminate\Database\QueryException] SQLSTATE[23000]: [Microsoft][SQL Server Native Client 11.0][SQL Server]Cann ot insert explicit value for identity column in table 'surveys' when IDENTITY_INSERT is set to OFF. (SQL: insert into [surveys] ([id], [name]) values (10, 'Some Text'))

注意:我正在尝试提供标识值,这可能是导致问题的原因.

Note: I am trying to supply the identity value which is probably what is causing the problem.

在研究SQL错误时,我了解到我需要执行以下查询.

While researching the SQL error, I learned that I need to execute the following queries.

在播种之前,我需要执行

Before seeding I need to execute

SET IDENTITY_INSERT surveys ON;

播种后,我需要执行

SET IDENTITY_INSERT surveys OFF;

但是我不确定如何使用Laravel执行这些命令

But I am not sure how can I execute these command using Laravel

在为Identity列提供值而又没有这个问题的情况下,如何播种?

How can I seed while supplying the value for the identity column without this issue?

已更新 这是我的播种机

UPDATED Here is my seeder

<?php

use Illuminate\Database\Seeder;

class FinalSurveyTS extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {   
        $myTable = 'surveys';

        DB::statement('SET IDENTITY_INSERT ' . $myTable . ' ON');


        DB::table($myTable)->truncate();


        DB::table($myTable)->insert([
            'id' => 10,
            'name' => 'some name',
        ]);

        DB::statement('SET IDENTITY_INSERT ' . $myTable . ' OFF');
    }
}

推荐答案

对于任何通过Google查找此问题的人-新的正确答案是使用unprepared(),如下所示:

For anyone finding this via Google - the new correct answer is to use unprepared() like this:

DB::beginTransaction();
DB::unprepared('SET IDENTITY_INSERT test ON');
DB::table('test')->insert(['id' => 1, 'name' => 'example']);
DB::unprepared('SET IDENTITY_INSERT test OFF');
DB::commit();

关于此问题的讨论线程: https://github.com/laravel/framework/issues /27778

As discussed on this issue thread: https://github.com/laravel/framework/issues/27778

这篇关于如何在MySQL上正确地将Laravel与SQL Server结合使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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