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条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?