php - 如何在 Eloquent 模型中动态设置表名

标签 php laravel laravel-5

我是 Laravel 的新手。我正在尝试使用 Eloquent 模型访问数据库中的数据。

我有一些表具有相似之处,例如表名。

所以我想使用一个模型访问数据库中的多个表,如下所示,但没有成功。

有没有办法动态设置表名?

如有任何建议或建议,我们将不胜感激。提前谢谢你。

型号:

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);
}

遇到同样问题的解决方法:

我能够按照@Mahdi Younesi 建议的方式更改表名。

我可以像下面这样添加 where 条件

$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
}

关于php - 如何在 Eloquent 模型中动态设置表名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47986628/

相关文章:

php - 在 SQL 中通过 SELECT AS 语法使用数组和循环

php - MongoDB/DocumentDB bson_append_array() : invalid array detected. 数组参数的第一个元素不是 "0"

php - 为 Paypal 付款添加折扣

php - 在 Laravel 中实现搜索 : Call to a member function posts() on null

laravel-5 - PDO异常 :SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket

php - Paypal Integration 持币

php - PHP 中 str_replace 的性能

php - 在迁移 laravel 5.1 中设置自动增量字段从 1000 开始

CSS 在 Laravel 中不起作用

php - Laravel 5 - 多对多关系 - 获取枢轴数据