2

i am little bit confused that how my query convert in laravel..

select users.username,users.photo, questions.*,
(Select count(*) from answers 
 where answers.q_id=questions.id) as aAccount from questions
 INNER JOIN users ON users.id=questions.user_id
3

2 Answers 2

2

Use Raw query

These expressions will be injected into the query as strings, so be careful not to create any SQL injection points! To create a raw expression, you may use the DB::raw method

    DB::table('questions')
    ->join('users', 'users.id', '=', 'questions.user_id')
    ->select('users.username','users.photo', 'questions.*',
    DB::raw("
    (   Select count(*) from answers 
        where answers.q_id=questions.id
    )as 'aAccount'")
    ->get();
Sign up to request clarification or add additional context in comments.

Comments

1

I upvoted JYoThl answer as it's exactly how I'd breakdown this query into eloquent, though in instances where a portion of your Eloquent query becomes raw, I personally prefer keeping the entire sql raw. You can still inject variables into it if required.

In my experience, the amount of time spent normalizing a more complex query like this will be used when you go back to the code to re-read it.

Here's how you would pass your sql in it's raw format. I also like to convert the array into a collection, as collections offer a variety of methods. Hope this helps!

$questions = collect(DB::select( DB::raw("
    select users.username,users.photo, questions.*, 
(Select count(*) from answers where answers.q_id=questions.id) as aAccount 
            from questions
                INNER JOIN users ON users.id=questions.user_id")
    ));

You would add variables into an array() area if you want to inject a variable. If you wanted to do that you would do something like this:

DB::select( DB::raw("select * from user where user = :user"), array('user' => $user))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.