How to dynamically set table name in Eloquent Mode

2020-02-06 02:27发布

I am new to Laravel. I am trying to use Eloquent Model to access data in DB.

I have tables that shares similarities such as table name.

So I want to use one Model to access several tables in DB like below but without luck.

Is there any way to set table name dynamically?

Any suggestion or advice would be appreciated. Thank you in advance.

Model:

class ProductLog extends Model
{

    public $timestamps = false;

    public function __construct($type = null) {

        parent::__construct();

        $this->setTable($type);
    }
}

Controller:

public function index($type, $id) {

    $productLog = new ProductLog($type);

    $contents = $productLog::all();

    return response($contents, 200);
}

Solution For those who suffer from same problem:

I was able to change table name by the way @Mahdi Younesi suggested.

And I was able to add where conditions by like below

$productLog = new ProductLog;
$productLog->setTable('LogEmail');

$logInstance = $productLog->where('origin_id', $carrier_id)
                          ->where('origin_type', 2);

1条回答
来,给爷笑一个
2楼-- · 2020-02-06 03:13

The following trait allows for passing on the table name during hydration.

trait BindsDynamically
{
    protected $connection = null;
    protected $table = null;

    public function bind(string $connection, string $table)
    {
       $this->setConnection($connection);
       $this->setTable($table);
    }

    public function newInstance($attributes = [], $exists = false)
    {
       // Overridden in order to allow for late table binding.

       $model = parent::newInstance($attributes, $exists);
       $model->setTable($this->table);

       return $model;
    }

}

Here is how to use it:

class ProductLog extends Model
{
   use BindsDynamically;
}

Call the method on instance like this:

public function index() 
{
   $productLog = new ProductLog;

   $productLog->setTable('anotherTableName');

   $productLog->get(); // select * from anotherTableName


   $productLog->myTestProp = 'test';
   $productLog->save(); // now saves into anotherTableName
}
查看更多
登录 后发表回答