BostonAreaHuman
BostonAreaHuman

Reputation: 1461

Laravel Eloquent setting up a subquery in the select part of the SQL

SELECT *, (
    SELECT count(id) FROM order_history oh 
    WHERE oh.refund_of = oh1.id
) "refunds"
FROM order_history oh1 
WHERE `object_name` 
NOT LIKE '%refund%'

I need to translate this into eloquent hopefully without using Db::raw

Upvotes: 0

Views: 411

Answers (1)

Joost
Joost

Reputation: 761

You should be able to add a sub select query with the method select() or addSelect() as shown here.

Example:

select(DB::raw(count(id) FROM order_history oh WHERE oh.refund_of = oh1.id))

Note: "These expressions will be injected into the query as strings, so be careful not to create any SQL injection points!"

Upvotes: 1

Related Questions