How to declare the table name dynamically in Laravel 5

本秂侑毒 提交于 2019-12-13 09:25:41

问题


I have to create the tables dynamically, so i need to declare the table name from controller. I need to access the variable in model like below :

use Illuminate\Database\Eloquent\Model;

class Transation extends Model
{    
    protected $table = 'Trans' . $this->userId;
}

How can i pass the variable to model?


回答1:


This works, but I don't know if it is the "laravel" way:

Transaction.php

public function __construct($params=array()) {
    if (isset($params['table'])) {
        $this->table = $params['table'];
    }
}

anyController.php

$transaction = new \App\Transaction(['table'=>'Trans' . $this->userId]);
// checking out
dd($transaction->getTable());


来源:https://stackoverflow.com/questions/32391681/how-to-declare-the-table-name-dynamically-in-laravel-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!