laravel 删除laravel迁移脚本中的测试数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34685953/
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
delete test data in laravel migration script
提问by user269867
I am trying to clean the test data from my production tables. In simple environment I can write a script to clean the test data but I wonder how can I do the same in laravel migration script
我正在尝试从我的生产表中清除测试数据。在简单的环境中,我可以编写一个脚本来清理测试数据,但我想知道如何在 Laravel 迁移脚本中执行相同的操作
I have a test user on production and want to clean all related records generated in the database.In a seed file I can fetch student id based on email address and then remove courses and other info based on the id?. I don't know if it sounds like a laravel way of doing things!
我有一个生产测试用户,想清除数据库中生成的所有相关记录。在种子文件中,我可以根据电子邮件地址获取学生 ID,然后根据 ID 删除课程和其他信息?。不知道是不是听起来像laravel的做事方式!
studentId = 101
学生 ID = 101
He is enrolled to three courses He has attendance records He has communication records
他注册了三个课程 他有出勤记录 他有交流记录
Now I want to fetch student id based on his emailId then want to delete records from courses, attendance, communication table and finally delete id from student table
现在我想根据他的 emailId 获取学生 id 然后想从课程、出勤、交流表中删除记录,最后从学生表中删除 id
I am doing
我在做
$sdetail = student::where('email','[email protected]')->first();
echo "you are checking fir: ".$sdetail ->id;
$classes= class::where('studentId',"$sdetail->id")->get();
foreach($classes as $class)
{
echo $class->name; //print only one record I have three rec!
DB::table('courses')->where("id",$class->id)->delete();
}
any idea fix this!
任何想法解决这个问题!
回答by Dan Johnson
You can run model functions within a migration - you just need to include the model at the top.
您可以在迁移中运行模型函数 - 您只需要在顶部包含模型。
use App\ModelName
class RemoveTestData extends Migration {
public function up(){
ModelName::where('id', $ID)->first()->delete();
}
public function down(){
ModelName::create([
//Test Data
]);
}
回答by YoJey Thilipan
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use App\Models\settings;
class ChangeCreateSettingsInsert extends Migration
{
public function up()
{
settings::create([
"product_id" => 1
]);
}
public function down()
{
settings::where('product_id',1)->delete();
}
}
回答by Dan Johnson
You can use the truncate()
function in a migration to remove all rows and reset any auto increment fields.
您可以truncate()
在迁移中使用该函数删除所有行并重置任何自动增量字段。
Schema::table('table_name', function($table)
{
$table->truncate();
});