Laravel - 动态创建表(无迁移)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30096105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:30:39  来源:igfitidea点击:

Laravel - Creating tables dynamically (without migration)

phpmysqllaraveldatabase-schema

提问by Shay

I'm trying to create a table dynamically upon an admin request, and while it seems all fun and dandy like in most of Laravel's documentation, I can't seem to createa table. Though I can drop tables, and add or drop columns as I wish.

我正在尝试根据管理员请求动态创建一个表,虽然在 Laravel 的大多数文档中看起来都很有趣和花哨,但我似乎无法创建一个表。虽然我可以删除表,并根据需要添加或删除列。

This is my basic code model:

这是我的基本代码模型:

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

public static function createTable() {

    Schema::create('randomName', function($table)
    {
        $table->increments('id');
        $table->string('name');
    });
}

What could possibly be the problem here? Unfortunately I don't receive any errors, so I don't know how to debug it. It just goes on to the next line, like everything's working fine. It just doesn't create any tables.

这里可能是什么问题?不幸的是我没有收到任何错误,所以我不知道如何调试它。它只是继续到下一行,就像一切正常。它只是不创建任何表。

Any advice? Much thanks in advance!

有什么建议吗?非常感谢提前!

回答by Shay

Ugh, never mind... I worked on it for long enough, and the solution as always was... Very simple.

呃,没关系……我已经研究了足够长的时间,而解决方案一如既往……非常简单。

I just had to figure a connection for the database first, so instead of

我只需要先确定数据库的连接,而不是

Schema::create('tableName', function($table)
{           
    $table->increments('id');
});

It is

这是

Schema::connection('mysql')->create('tableName', function($table)
{
    $table->increments('id');
});

Hope this helps someone someday in the future!

希望这对将来的某个人有所帮助!

回答by YakuZa

This one is even better.

这个更好。

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

Schema::create('tableName', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
    });