如何在 laravel 的 eloquent ORM 中正确使用 orderByRaw?

How to use orderByRaw correctly in laravel's eloquent ORM?

所以我正在 Eloquent 中尝试一些复杂的排序过滤器。所以我有一个patent_texttable。这是它的迁移 table:

        Schema::create('patent_text', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('patent_id')->unsigned()->index('patent_id');
            $table->enum('text_type', array('ICLAIM', 'CLAIM', 'DESCRIPTION', 'ABSTRACT', 'TITLE'))->nullable();
            $table->enum('type', array('ORIGINAL', 'MACHINE'))->nullable();
            $table->string('language', 2)->nullable();
            $table->longText('text')->nullable();
            $table->timestamps();

            $table->foreign('patent_id',
                'patent_text_ibfk_1')->references('id')->on('patent')->onUpdate('RESTRICT')->onDelete('CASCADE');

        });

所以现在我尝试按 text_type 订购,我想先订购 ORIGINAL,然后订购 MACHINE,但这很容易。

我只是 $this->texts->orderBy('text_type'); 并且效果很好。 ORIGINAL 文本放在第一位,然后是其他文本。

但我也想按语言字段排序。我希望 en 排在首位,然后是其他人。所以我试过 orderByRaw 像这样:

$this->texts()->orderBy('text_type')->orderByRaw("FIELD(language , 'en', 'se') ASC")->get()

但它没有用,我不知道我错过了什么。

您可以将 orderByRawCASE 一起使用,而不是像

那样使用 FIELD
->orderByRaw("CASE WHEN language = 'en' THEN 0 WHEN language = 'se' THEN 0 ELSE 1 END")