Sunday, 9 May 2021

Laravel elqouent setting model name as alias has problem with insert

 https://stackoverflow.com/questions/17713730/how-to-alias-a-table-in-laravel-eloquent-queries-or-using-query-builder


To use in Eloquent. Add on top of your model

protected $table = 'table_name as alias'

//table_name should be exact as in your database

..then use in your query like

ModelName::query()->select(alias.id, alias.name)



This has a problem that it will fail with inserts as


insert into `table_name ` as `alias` (`column_a`, `column_b`) values (1, 0)



will be invalid,



to fix this,

in the model table_name

create a function called insert()

and use DB::table from Illuminate\Support\Facades\DB;


public function insert(array $data) { // returns inserted Id return DB::table('table_name')->insertGetId($data); }

No comments:

Post a Comment