laravel 如何在 Eloquent 模型中动态设置表名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47986628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to dynamically set table name in Eloquent Model
提问by smchae
I am new to Laravel. I am trying to use Eloquent Model to access data in DB.
我是 Laravel 的新手。我正在尝试使用 Eloquent 模型访问 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.
我能够按照@Mahdi Younesi 建议的方式更改表名。
And I was able to add where conditions by like below
我可以通过如下方式添加 where 条件
$productLog = new ProductLog;
$productLog->setTable('LogEmail');
$logInstance = $productLog->where('origin_id', $carrier_id)
->where('origin_type', 2);
回答by Mahdi Younesi
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
}