php 如何对模型执行删除操作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29156192/
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-08-26 00:16:17  来源:igfitidea点击:

How to perform a delete operation on a Model?

phplaravelsqliteeloquentlaravel-5

提问by Sylar

Coming from a Ruby on Rails experience where you load up the rails console to delete a user or all users. I am new to Laravel 5 and I am looking for something similar to delete a user already in the sqlite3 database.

来自 Ruby on Rails 体验,您可以加载 Rails 控制台以删除用户或所有用户。我是 Laravel 5 的新手,我正在寻找类似的东西来删除 sqlite3 数据库中已有的用户。

I see where people are talking about User::find(1)->delete();to delete a user but where to you put that and run in? Is there a console to perform a delete task in? I would like to know how to delete a user without dropping the table. I do not want to soft delete.

我看到人们在谈论User::find(1)->delete();删除用户的地方,但你把它放在哪里并运行?是否有控制台可以执行删除任务?我想知道如何在不删除表的情况下删除用户。我不想软删除。

回答by Marcin Nabia?ek

You can put this code for example in controller.

例如,您可以将此代码放在控制器中。

You can use

您可以使用

$user = User::find($id);    
$user->delete();

if you don't use SoftDeletingTraittrait or

如果你不使用SoftDeletingTraittrait 或

$user = User::find($id);    
$user->forceDelete();

if you do, and you want to really remove user from database, not just hide it from results.

如果您这样做,并且您想真正从数据库中删除用户,而不仅仅是将其从结果中隐藏。

More you can read at Laravel page

您可以在Laravel 页面阅读更多内容

回答by Jeff

in Laravel 5 you can use the destroy method.

在 Laravel 5 中你可以使用 destroy 方法。

$user->destroy($id);

and, sure, you have a command line to do so.

当然,您有一个命令行可以这样做。

$ php artisan tinker

and you can run for example

你可以运行例如

>> $var = new App\User;
>> $user= $user->find($id);
>> $user->destroy();

回答by Alex Cook

Several ways to do this.

有几种方法可以做到这一点。

If your controller defines the user as an argument:

如果您的控制器将用户定义为参数:

public function destroy(User $user) 
{
    return $user->delete();
}

You can also delete any user by $id:

您还可以通过 $id 删除任何用户:

User::destroy ($id);

Assuming you're wrapping these routes with some security.

假设您以某种安全性包装这些路由。

Edit: Corrected spelling

编辑:更正拼写

回答by Shanka SMS

You can use bellow example to delete data with multiple parameters......

您可以使用下面的示例删除具有多个参数的数据......

> 
> tableName::where('field_1','=',$para1)
>               ->where('field_2,'=',$para2)
>               ->delete();

回答by Oussema Miled

This still works with laravel 7, i use tinkercommand line and the delete() method:

这仍然适用于 laravel 7,我使用tinker命令行和 delete() 方法:

php artisan tinker

Now i can run commands directly:

现在我可以直接运行命令:

> App\User::find($id)->delete();