如何在laravel中向模型传递变量以创建动态表名

iq3niunx  于 2022-12-24  发布在  其他
关注(0)|答案(1)|浏览(152)

我试图在运行时创建基于用户ID和用户名的表名。但是,我无法做到这一点。任何帮助都非常感谢。

<?php

namespace App;
use Illuminate\Database\Eloquent\Model;
use Auth;
use App\User;

class Transaction extends Model
{
    $id = Auth::user()->id;
    $name = user::find($id)->name; 
    $table_name = 'tumble'.'__'.$name.'_'.$id; 
    protected $table = $table_name;   
}
hfyxw5xn

hfyxw5xn1#

可以使用架构生成器创建表

<?php

namespace App;
use Illuminate\Database\Eloquent\Model;
use Auth;
use App\User;

class Transaction extends Model
{
    $id = Auth::user()->id;
    $name = user::find($id)->name; 
    $table_name = 'tumble'.'__'.$name.'_'.$id; 
    protected $table = $table_name;   
$this->createTable($tableName);
}

private function createTable($tableName)
{
Schema::create($tableName, function($table)
{
    $table->increments('id');
    // set here you columns just like migration ...
});
}

相关问题