Home > Software engineering >  Laravel query builder select all except specific column
Laravel query builder select all except specific column

Time:05-18

I have 2 tables with the same columns except the second table have one more column, this column is foreign key of the first;

what i want is to make union query;but for union the column must the same; so i want to select all column except for the column distinct;

The easy way is to provide in select all the same column:

$a = Table1::select(['column1', 'column2', 'etc...']);
$b = Table2::select(['column1', 'column2', 'etc...']);

and go with $a->union($b)->get();

but if i have too much column, i end up with so much column to provide in the select function; so what i want is to provide in the query the column that i don't want to retrieve;

i can put protected $hidden in the second table model but for some reason i need this distinct column on some other query;

CodePudding user response:

Get all columns name by Schema::getColumnListing($table);

And computes the intersection of arrays

array_intersect($columnsName1, $columnsName2);

CodePudding user response:

I haven't done it with 2 tables but I am using collections and rejecting certain columns on a similar project:-

$row = Table1::firstOrFail();

$exclude=['column_1', 'column_2'];

return collect(array_keys($row->getAttributes()))
    ->reject(function ($name) use ($row, $exclude) {
        return in_array($name, $row->getHidden())
            || in_array($name, $exclude);
    }
);
  • Related