【问题标题】:How to dynamically set table name in Eloquent Model如何在 Eloquent 模型中动态设置表名
【发布时间】: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 方法,但您也许可以使用查询范围并在其中设置表名。

标签: php laravel laravel-5


【解决方案1】:

以下特征允许在水合期间传递表名。

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
}

【讨论】:

  • 它改变了表名,但是在我使用$productLog->setTable('anotherTableName');之后,如果我使用$productLog->where('some query'),它就不起作用了。
猜你喜欢
  • 2015-02-21
  • 1970-01-01
  • 2019-01-29
  • 1970-01-01
  • 1970-01-01
  • 2014-10-24
  • 1970-01-01
  • 2021-04-30
  • 1970-01-01
相关资源
最近更新 更多