[英]How to use orderByRaw correctly in laravel's eloquent ORM?
So I am trying a few complex ordering filters in Eloquent. 所以我正在Eloquent中尝试一些复杂的排序过滤器。 So I have a patent_text table. 所以我有一个patent_text表。 Here is the migration table for it: 这是它的迁移表:
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');
});
So now I am trying to order by text_type
and I want to have ORIGINAL
first and then MACHINE
but that is easy. 因此,现在我尝试按text_type
进行订购,我想先拥有ORIGINAL
,然后再获得MACHINE
但这很容易。
I just do $this->texts->orderBy('text_type');
我只是做$this->texts->orderBy('text_type');
and it works just fine. 而且效果很好。 The ORIGINAL
texts are put first and then the other ones. ORIGINAL
文本放在首位,然后放置其他文本。
But I also want to order by the language field. 但我也想按语言字段排序。 I want en
to be on top and then others. 我想让en
成为第一,然后是其他。 So I tried orderByRaw
like so: 所以我像这样尝试了orderByRaw
:
$this->texts()->orderBy('text_type')->orderByRaw("FIELD(language , 'en', 'se') ASC")->get()
But it did not work and I cannot figure out what I am missing. 但这没有用,我无法弄清我所缺少的。
您可以与CASE
一起使用orderByRaw
而不是FIELD
例如
->orderByRaw("CASE WHEN language = 'en' THEN 0 WHEN language = 'se' THEN 0 ELSE 1 END")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.