Laravel PHPUnit 错误 mysql 全文索引

Laravel PHPUnit error mysql fulltext index

添加全文索引

后 Laravel 中的 运行 PHPUnit 出现错误
Doctrine\DBAL\Driver\PDOException: SQLSTATE[HY000]: General error: 1 near "name": syntax error

经查,是我添加的migration导致的错误

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddFulltextIndexToProductName extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        DB::statement('ALTER TABLE products ADD FULLTEXT fulltext_index(name)');
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        DB::statement('DROP INDEX `fulltext_index`');
    }
}

如果我删除那个迁移代码,测试 运行 优雅

有人遇到过这个问题吗?

通常 Laravel 测试在内存中使用 sqlite 数据库,并且迁移中的此语句将不起作用。 您可以在此处查看如何创建 sqlite 全文索引:https://www.sqlitetutorial.net/sqlite-full-text-search/

由于 Laravel 不支持开箱即用的全文搜索,我假设您已经编写了自定义函数,该函数可能在测试中也不起作用。

要解决此问题,您可以:

  • 使用mysql进行测试(不推荐,因为它很慢)
  • 使用存储库模式
  • 在测试时跳过迁移(如果你不是 测试搜索 - 你不需要它)。你可以检查 if(env('APP_ENV') === 'testing')
  • 使用 laravel 球探进行搜索