I need to have 1 model where I can switch out the connection and table name. This seems to be almost working, however if I remove the orderBy
then the where
clause isn't added to the query.
$table
is a collection which contains my table name.
This is the model:
DynamicModel.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class DynamicModel extends Model
{
public function scopeSet($query, $table, $connection)
{
$this->setTable($table);
$this->setConnection($connection);
return $this;
}
}
This is how i'm changing the table name:
$result = DB::select(DB::raw("SHOW KEYS FROM {$table->getAttribute('table')} WHERE Key_name = 'PRIMARY'"));
$primaryKey = $result[0]->Column_name;
/** @var Model $demo */
$demo = DynamicModel::set($table->getAttribute('table'), 'demo')->orderBy($primaryKey);
$demo->where([ 'dealer_id' => $website->dealer_id ]);
$demoData = $demo->toSql();
So, this is the resulting SQL with the orderBy
clause.
select * from
tablename
where (dealer_id
= ?) order byda_id
asc
But if I remove the orderBy
clause then I get this:
select * from
tablename
Any ideas?