W
W
WebDev2016-04-09 15:35:40
Laravel
WebDev, 2016-04-09 15:35:40

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

In Eloquent, as far as I understand, you cannot use a select inside a join.
Google advises to insert DB::raw inside JOIN
#
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();

It really works and I did like this:
- Inner query got via toSql()
$sql = Model::where(...)->toSql();
Then this sql inserted into join
#
Entity::leftJoin(\DB::raw('(' . $sql . ') AS LJ'), function($join) {
                $join->on('entities.id', '=', \DB::raw('LJ.entity_id'));
            })
            ->selectRaw('...');

As a result, the script swears, because as a result, a query with "?" instead of values.
#
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

That is, you need to substitute a really "raw" query in DB::raw, and not generated via toSql (), but I need it through toSql (), because I use scope for an internal query.
What can be done?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
D', 2016-04-09
@kirill-93

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;

But it kinda smells :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question