dph23577 2018-02-12 12:54
浏览 275
已采纳

如何在Laravel Eloquent中使用内部联接和子查询

Note: this is laravel 5.3

Basically I'm running a query when a user selects arabic translation.. the full sql looks like this

select s.ref, t.text as ref_ar 
  FROM stores AS s 
  INNER JOIN 
     (SELECT item, text 
      FROM translator_translations 
      WHERE locale ='ar' 
        AND namespace ='*' 
        AND item like 'store.ref%'
      ) AS t 
   ON substring(s.ref_translation from 14 for 26) = t.item;

don't see much documentation on subqueries on the official Laravel docs (there are inner join stuff but not good enough) and the SO advice seems extra-hacky.. advice?

context

this will be used as a scope inside a model, so this works for example:

public function scopeFilterLanguage($query, $language_id)
{
    if (!$language_id || intval($language_id) != LanguageConstants::ARABIC_LANGUAGE_ID) {
        return $query;
    }
    return $query->whereRaw("
    substring(ref_translation from 14 for 26) in 
                                    (select item 
                                     from 
                                     translator_translations 
                                     where 
                                     locale ='ar' and namespace ='*' 
                                     and 
                                     item like 'store.ref%')");

}

but it doesn't give me what i want. (ie i have to use the bigger version at the start of this post)

  • 写回答

2条回答 默认 最新

  • dongwen2794 2018-02-14 19:57
    关注

    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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题