【发布时间】:2017-12-27 05:08:50
【问题描述】:
我是 Laravel 的新手。我正在尝试使用 Eloquent 模型访问数据库中的数据。
我的表具有相似之处,例如表名。
所以我想使用一个模型来访问数据库中的多个表,如下所示,但没有运气。
有没有办法动态设置表名?
任何建议或意见将不胜感激。提前谢谢你。
型号:
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 的建议更改表名。
我可以通过如下方式添加 where 条件
$productLog = new ProductLog;
$productLog->setTable('LogEmail');
$logInstance = $productLog->where('origin_id', $carrier_id)
->where('origin_type', 2);
【问题讨论】:
-
那么,你想每次传递不同的表名吗?
-
是的。仅适用于某些表格;具有相似属性的表。
-
我可以建议您为所有表制作模型,但我可以告诉您一个通用函数,该函数将通过仅将模型名称传递给该函数来制作任何模型的对象,您将动态获取模型对象.
-
如果这是绝对必要的,您可以覆盖
getTable方法,但您也许可以使用查询范围并在其中设置表名。