Answer the question
In order to leave comments, you need to log in
Laravel toSql to DB::raw?
Hello, can you tell me how can I insert a sql query received via toSql() into DB::raw?
It was necessary to transfer such a request to Eloquent:
#
SELECT * FROM a
LEFT JOIN (
SELECT * FROM b WHERE ...
) AS Q2 ON Q2.id = a.id
#
DB::table('users') ->select('first_name', 'TotalCatches.*')
->join(DB::raw('(SELECT ...) TotalCatches'), function($join) {
$join->on('users.id', '=', 'TotalCatches.user_id');
})
->orderBy('TotalCatches.CatchesPerDay', 'DESC')
->get();
$sql = Model::where(...)->toSql();
#
Entity::leftJoin(\DB::raw('(' . $sql . ') AS LJ'), function($join) {
$join->on('entities.id', '=', \DB::raw('LJ.entity_id'));
})
->selectRaw('...');
#
select ...
from `bq_entities`
left join (
select *
from `bq_posts`
where `entity_id` in (?) and `id` not in (?)
) AS LJ on `bq_entities`.`id` = LJ.entity_id
Answer the question
In order to leave comments, you need to log in
If you answer on the topic of the question, then you can make such a crutch:
$builder = Model::where('....');
$sql = $builder->toSql();
$bindings = $builder->getBindings();
foreach ($bindings as $binding) {
$value = is_numeric($binding) ? $binding : "'".$binding."'";
$sql = preg_replace('/\?/', $value, $sql, 1);
}
echo $sql;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question