我是Laravel的新手.我试图使用Eloquent Model来访问DB中的数据.
我有表与表名相似的表.
所以我想使用一个Model来访问DB中的几个表,但是没有运气.
有没有办法动态设置表名?
任何建议或意见将不胜感激.先感谢您.
模型:
class ProductLog extends Model
{
public $timestamps = false;
public function __construct($type = null) {
parent::__construct();
$this->setTable($type);
}
}
控制器:
public function index($type, $id) {
$productLog = new ProductLog($type);
$contents = $productLog::all();
return response($contents, 200);
}
解决方案对于那些遭受同样问题的人:
我能够通过@Mahdi Younesi建议的方式更改表名.
我能够通过以下方式添加条件
$productLog = new ProductLog;
$productLog->setTable('LogEmail');
$logInstance = $productLog->where('origin_id', $carrier_id)
->where('origin_type', 2);
解决方法:
以下特性允许在水合期间传递表名.
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;
}
}
以下是如何使用它:
class ProductLog extends Model
{
use BindsDynamically;
}
public function index()
{
$productLog = new ProductLog;
$productLog->setTable('anotherTableName');
$productLog->get(); // select * from anotherTableName
$productLog->myTestProp = 'test';
$productLog->save(); // Now saves into anotherTableName
}