与联接Laravel的Orderby检查空结果

时间:2018-12-21 09:49:32

标签: php laravel

我有这种关系:

strtok

在表 public function romwords() { return $this->hasMany('App\RomWord', 'dwruId', 'dwruId') ->leftJoin('dwords_ro_black', 'dwords_ro_black.dwroId', '=', 'dwords_ro.dwroId') ->orderBy('isMd', 'desc'); } 上的列isMd。在表dwords_ro上,只有列dwords_ro_blackid

仅当leftJoin为空(空结果)时,我才需要使用{By {1}}列的orderBy。 我该如何检查?

1 个答案:

答案 0 :(得分:0)

尝试一下:

public function romwords()
{
    return $this
        ->hasMany('App\RomWord', 'dwruId', 'dwruId')
        ->leftJoin('dwords_ro_black', 'dwords_ro_black.dwroId', '=', 'dwords_ro.dwroId')
        ->orderByRaw('
            CASE
                WHEN dwords_ro_black.id IS NULL THEN 1
                WHEN dwords_ro.isRo = 1 AND dwords_ro.isMd = 1 THEN 1
                WHEN dwords_ro.isMd = 1 THEN 0
                WHEN dwords_ro.isRo = 1 THEN 2
            END
        ');
}