How to dynamically set table name in Eloquent Model(如何在 Eloquent 模型中动态设置表名)
问题描述
我是 Laravel 的新手.我正在尝试使用 Eloquent 模型访问数据库中的数据.
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.
型号:
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 建议的方式更改表名.
I was able to change table name by the way @Mahdi Younesi suggested.
我可以通过如下方式添加 where 条件
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);
推荐答案
以下 trait 允许在 hydration 期间传递表名.
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;
}
}
使用方法如下:
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
}
这篇关于如何在 Eloquent 模型中动态设置表名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Eloquent 模型中动态设置表名
基础教程推荐
- HTTP 与 FTP 上传 2021-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01