How to use inner joins with subqueries in Laravel Eloquent

こ雲淡風輕ζ 提交于 2019-12-06 08:20:43

this worked (ignore the dynamic stuff like this->getClassName etc).. the basic logic works just fine

public function scopeAddTranslations($query)
{
    $t = new Translation();

    $subq = $t->select('item','text as ref_ar')
              ->where('locale','=','ar')
              ->where('item','like',$this->getClassName().'.ref%');

    $query->leftjoin(\DB::raw('('.$subq->toSql().') as t'), 
      function ($join) use ($subq) { 
          $join->on(\DB::raw('SUBSTRING('.$this->getTable().'.ref_translation 
                              FROM 14 FOR 26)'),
                                 '=',
                                 \DB::raw('t.item'))
                   ->addBinding($subq->getBindings());
            });
    return $query;
}

Here's my completely untested and best guess effort.

public function scopeFilterLanguage($query, $language_id)
{
    if (!$language_id || intval($language_id) != LanguageConstants::ARABIC_LANGUAGE_ID) {
        return $query;
    }
    return $query->join('translator_translations', function($join) {
        $join->selectSub(function($q) {
               $q->where('t.locale' => 'ar')
               $q->where('t.namespace', '*')
               $q->where('t.item', 'like', $this->ref . '%')
          }, 't');
     })->on('t.item', '=', substr($this->ref_translation, 14, 26))
       ->select('t.text', 'ref');
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!