问题
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)
回答1:
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;
}
回答2:
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');
}
来源:https://stackoverflow.com/questions/48747008/how-to-use-inner-joins-with-subqueries-in-laravel-eloquent