在SQLite中,外键约束是disabled by default。
配置Laravel 5.1的SQLite数据库连接以启用外键约束的最佳方法是什么?我没有在['connections']['sqlite']
的/config/database.php
看到这样做的方法。
这是一个解决方案。在boot()
的App\Providers\AppServiceProvider
方法中,添加:
if (DB::connection() instanceof \Illuminate\Database\SQLiteConnection) {
DB::statement(DB::raw('PRAGMA foreign_keys=1'));
}
感谢@RobertTrzebinski为this blog post关于Laravel 4。
对我来说,使用Laravel 5.2中App \ Providers \ AppServiceProvider中的Facade DB产生了错误。这是我的解决方案:
if(config('database.default') == 'sqlite'){
$db = app()->make('db');
$db->connection()->getPdo()->exec("pragma foreign_keys=1");
}
因为我只想在我的测试中使用它,但在所有测试中,我最终在Tests\TestCase
类中使用了这样一个简单的实现:
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
protected function setUp()
{
parent::setUp();
$this->enableForeignKeys();
}
/**
* Enables foreign keys.
*
* @return void
*/
public function enableForeignKeys()
{
$db = app()->make('db');
$db->getSchemaBuilder()->enableForeignKeyConstraints();
}
}
这就像一个魅力:-)
当测试实际上依赖于具有外键的表时,您还可以基于每个测试(文件)激活外键。
这是一个特点:(例如tests/ForeignKeys.php
)
<?php
namespace Tests;
trait ForeignKeys
{
/**
* Enables foreign keys.
*
* @return void
*/
public function enableForeignKeys()
{
$db = app()->make('db');
$db->getSchemaBuilder()->enableForeignKeyConstraints();
}
}
不要忘记在测试设置链中的某处运行该方法。我添加了我的替代我的TestCase:(tests/TestCase.php
)
<?php
namespace Tests;
/**
* Class TestCase
* @package Tests
* @mixin \PHPUnit\Framework\TestCase
*/
abstract class TestCase extends \Illuminate\Foundation\Testing\TestCase
{
use CreatesApplication;
...
/**
* Boot the testing helper traits.
*
* @return array
*/
protected function setUpTraits()
{
$uses = parent::setUpTraits();
if (isset($uses[ForeignKeys::class])) {
/* @var $this TestCase|ForeignKeys */
$this->enableForeignKeys();
}
}
...
之后,您可以将它添加到您的测试中,如下所示:
<?php
namespace Tests\Feature;
use Tests\ForeignKeys;
use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseMigrations;
class ExampleFeatureTest extends TestCase
{
use DatabaseMigrations;
use ForeignKeys;
...