如何在laravel中传递变量以进行建模以创建动态表名称

问题描述 投票:0回答:1

我正在尝试根据用户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;   
}
laravel variables model
1个回答
0
投票

您可以使用schema builder创建表

<?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 ...
});
}
© www.soinside.com 2019 - 2024. All rights reserved.