如何在Eloquent Model中动态设置表名

smc*_*hae 6 php laravel laravel-5

我是Laravel的新手.我试图使用Eloquent Model来访问DB中的数据.

我有表与表名相似的表.

所以我想使用一个模型来访问DB中的几个表,但是没有运气.

有没有办法动态设置表名?

任何建议或意见将不胜感激.先感谢您.

模型:

class ProductLog extends Model
{

    public $timestamps = false;

    public function __construct($type = null) {

        parent::__construct();

        $this->setTable($type);
    }
}
Run Code Online (Sandbox Code Playgroud)

控制器:

public function index($type, $id) {

    $productLog = new ProductLog($type);

    $contents = $productLog::all();

    return response($contents, 200);
}
Run Code Online (Sandbox Code Playgroud)

解决方案对于那些遭受同样问题的人:

我能够通过@Mahdi Younesi建议的方式更改表名.

我能够通过以下方式添加条件

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

$logInstance = $productLog->where('origin_id', $carrier_id)
                          ->where('origin_type', 2);
Run Code Online (Sandbox Code Playgroud)

Mah*_*esi 11

以下特性允许在水合期间传递表名.

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;
    }

}
Run Code Online (Sandbox Code Playgroud)

以下是如何使用它:

class ProductLog extends Model
{
   use BindsDynamically;
}
Run Code Online (Sandbox Code Playgroud)

像这样在实例上调用方法:

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

   $productLog->setTable('anotherTableName');

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


   $productLog->myTestProp = 'test';
   $productLog->save(); // now saves into anotherTableName
}
Run Code Online (Sandbox Code Playgroud)

  • 它更改了表名,但在我使用 `$productLog->setTable('anotherTableName');` 之后,如果我要使用 `$productLog->where('some query')`,则它不起作用。 (2认同)