Laravel 5.2 - 从控制器创建数据库表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36361172/
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
Laravel 5.2 - Create Database table from a Controller
提问by Inigo EC
Apologies if this have been asked, but I don't seem to find the right answer.
如果有人问过这个,我很抱歉,但我似乎没有找到正确的答案。
I need to create a table in the DB from a Controller.
我需要从控制器在数据库中创建一个表。
I was naive enough to believe the below would work:
我天真到相信下面的方法会奏效:
Schema::connection('mysql')->create('mytable_'.$id, function($table)
{
$table->increments('id');
$table->timestamps();
});
Where $id
is a dynamic value passed into the controller's function.
$id
传递给控制器函数的动态值在哪里。
I've placed the below on the top:
我已将以下内容放在顶部:
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
No luck - How can a DB table be created from the controller then? Any ideas?
不走运 - 那么如何从控制器创建数据库表?有任何想法吗?
SolutionAs Ben Swinburne has said in the first comment, the use Schema
was missing!
解决方案正如 Ben Swinburne 在第一条评论中所说,use Schema
丢失了!
采纳答案by Ben Swinburne
You're using the Schema
facade.
您正在使用Schema
外观。
Make sure you have use Schema;
at the top of your file too.
确保您use Schema;
的文件顶部也有。
回答by Alexey Mezenin
I think best approach will be creating a migration and running php artisan migrate
command from your controller:
我认为最好的方法是从您的控制器创建迁移和运行php artisan migrate
命令:
Artisan::call('migrate');
If you do not know how to create migrations from code using stubs
, you can learn that from some well-written package. I've learned how to do that from this package.
如果您不知道如何使用从代码创建迁移stubs
,您可以从一些编写良好的包中学习。我已经从这个包中学会了如何做到这一点。
Hope this will help
希望这会有所帮助