3
votes

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?

1
Is there a reason you don't want to use Eloquent ORM?WhyAyala
This is a complex query across tables with joins so doesn't really lend itself to eloquentConnor Leech

1 Answers

4
votes

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