5

I have a Laravel Eloquent query where I am trying to select multiple columns from a MySQL table.

    $query = DB::connection('global')
        ->select(
            'mytable.id',
            'mytable.column1',
            'mytable.another_column',
            'mytable.created_at',
            'myothertable.id
        )
        ->from('mytable')
        ->get();

It looks like the select() function takes three arguments: query, bindings and useReadPdo. The above query gives me an error:

{"error":true,"message":"Type error: Argument 1 passed to Illuminate\\Database\\Connection::prepareBindings() must be of the type array, string given" }

How do I write a select with Laravel query builder for the above columns?

I am structuring the query in this way, because I am looking to have a join across another table like so:

    $query = DB::connection('global')
        ->select(
            'mytable.id',
            'mytable.column1',
            'mytable.another_column',
            'mytable.created_at',
            'myothertable.id
        )
        ->from('mytable')
        ->leftJoin('myothertable', function($join){
           $join->on('mytable.id', '=', 'myothertable.id');
        })
        ->get();

How do I use the select function to grab multiple columns across tables with Eloquent query builder?

2
  • Is there a reason you don't want to use Eloquent ORM? Commented Feb 6, 2018 at 23:39
  • This is a complex query across tables with joins so doesn't really lend itself to eloquent Commented Feb 7, 2018 at 0:12

1 Answer 1

7

How do I write a select with Laravel query builder for the above columns?

You can do:

$data = DB::table('mytable')
        ->join('myothertable', 'mytable.id', '=', 'myothertable.mytable_id')
        ->select(
            'mytable.id',
            'mytable.column1',
            'mytable.another_column',
            'mytable.created_at',
            'myothertable.id'
        )
        ->get();

You can read the documentations here

Sign up to request clarification or add additional context in comments.

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.