1
votes

I have a laravel mysql query to select a column named title and the table name as Source

$query = DB::select('select title, "'.$table_name.'" as source from ' . $table_name);

but this returns an array, and I want to perform union query for the above query. So I adopted the laravel DB::table()

DB::table($table_name)->select('title, "'.$table_name.'" as source')

But the above query returns an error unknown column name.

SQLSTATE[42S22]: Column not found: 1054 Unknown column '"tablename"' in 'field list' (SQL: select title, "tablename" as source from tablename)

I just want to add another field named source and put the table name in all rows.

I repeat the same for number of tables and finally sort them before rendering. Please help me out.

Thank you in advance.

1
I would suggest binding as laravel documentaion says but it won't work in your case because you are trying to bind table namesGaimZz
maybe this works $select = "select title, ".$table_name." as source from " . $table_name; then DB::select($select);GaimZz
It worked. But still returns an array so I can't perform union query.Prasanna Kumar

1 Answers

2
votes

I found the solution. This post helped me.

$row = sprintf('"%s" AS source', $tablename);
$query = DB::table($tablename)->select('title', DB::raw($row));