php 在 Laravel 5 中截断表格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33054706/
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
Truncate a table in Laravel 5
提问by cyber8200
Description: I have a table full of tested data. Sometimes, I want to clear it out for new data. I can perform the truncate in the DBMS App like MySQL WorkBench, but I'm trying to achieve it within my application instead.
描述:我有一个充满测试数据的表格。有时,我想清除它以获取新数据。我可以在 DBMS 应用程序中执行截断,如MySQL WorkBench,但我试图在我的应用程序中实现它。
Goal: to make a button to truncate a table in a database when on click.
目标:制作一个按钮,在点击时截断数据库中的表格。
Here are my steps :
这是我的步骤:
1 - Declare a route
1 - 声明路线
Route::delete('visitor/truncate',array('as'=>'visitor.truncate', 'uses'=>'VisitorController@truncate'));
2 - Create a truncate
function in my VisitorController
2 -truncate
在 my 中创建一个函数VisitorController
public function truncate()
{
$visitors = Visitor::all();
$visitors ->truncate();
return View::make('visitors.index')
->with('success', 'Truncate Done');
}
3 - Create a button on my view
3 - 在我的视图上创建一个按钮
{!! Form::model($visitors, array( 'route' => array('visitor.truncate'),'method' => 'DELETE')) !!}
<button type="submit" class="btn bgm-red btn-float waves-effect waves-effect waves-button waves-float"><i class="md md-remove"></i></button>
{!! Form::close()!!}
4 - Test
4 - 测试
When I click on it, it get into my truncate()
function in my controller, but I keep getting this error
当我点击它时,它进入truncate()
我的控制器中的功能,但我不断收到此错误
Call to undefined method Illuminate\Database\Eloquent\Collection::truncate()
调用未定义的方法 Illuminate\Database\Eloquent\Collection::truncate()
Do I need include anything to use truncate()
?
我需要包含任何东西truncate()
吗?
Any hints on that will be much appreciated !
对此的任何提示将不胜感激!
回答by Bogdan
The truncate
method is part of the Query Builder. However Visitor::all()
returns a Collection
instance. You need to build the query using the following:
该truncate
方法是查询生成器的一部分。但是Visitor::all()
返回一个Collection
实例。您需要使用以下内容构建查询:
Visitor::query()->truncate();
回答by nasirkhan
the following should work as well,
以下也应该有效,
Visitor::truncate();
Visitor::truncate();
回答by Ryan
From the Laravel Docs
来自 Laravel 文档
https://laravel.com/docs/5.6/queries#deletessays:
https://laravel.com/docs/5.6/queries#deletes说:
If you wish to truncate the entire table, which will remove all rows and reset the auto-incrementing ID to zero, you may use the
truncate
method:
DB::table('users')->truncate();
如果您希望截断整个表,这将删除所有行并将自动递增 ID 重置为零,您可以使用以下
truncate
方法:
DB::table('users')->truncate();
回答by itz_nsn
another way if you dont have a model class for the table - Laravel 5.4
如果您没有表格的模型类,另一种方式 - Laravel 5.4
DB:connection(database connection name)->table(table name)->truncate();