微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 如何在Eloquent Model中动态设置表名

我是Laravel的新手.我试图使用Eloquent Model来访问DB中的数据.

我有表与表名相似的表.

所以我想使用一个Model来访问DB中的几个表,但是没有运气.

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

任何建议或意见将不胜感激.先感谢您.

模型:

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建议的方式更改表名.

我能够通过以下方式添加条件

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐