php Laravel 中的 destroy() 和 delete() 方法有什么区别?

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

What is the difference between destroy() and delete() methods in Laravel?

phplaravellaravel-4eloquent

提问by phoops

I'm having a minor issue with Laravel 4. I'd like to use the delete()method on a record but for some reason it doesn't actually delete the record. destroy()does, though, so my code is good. Also, if I pass Teetime::where('date', '=', $formattedDate)->count()to my view I get one which is correct. What's the problem?

我在 Laravel 4 中遇到了一个小问题。我想delete()在记录上使用该方法,但由于某种原因,它实际上并没有删除记录。destroy()确实如此,所以我的代码很好。另外,如果我传递Teetime::where('date', '=', $formattedDate)->count()给我的观点,我会得到一个正确的观点。有什么问题?

        if($action=="delete") {
            $teetime = Teetime::where('date', '=', $formattedDate)->firstOrFail();
            // for some reason $teetime->delete() doesn't work
            Teetime::destroy($teetime->id);
        }

回答by phoops

  • destroyis correct method for removing an entity directly (via object or model).
  • destroy是直接(通过对象或模型)删除实体的正确方法。

Example:

例子:

$teetime = Teetime::where('date', '=', $formattedDate)->firstOrFail();
$teetime->destroy();
  • deletecan only be called in query builder
  • delete只能在查询构建器中调用

Example:

例子:

$teetime = Teetime::where('date', '=', $formattedDate)->delete();

From documentation:

从文档:

Deleting An Existing Model By Key

通过键删除现有模型

User::destroy(1);

User::destroy(array(1, 2, 3));

User::destroy(1, 2, 3);

Of course, you may also run a delete query on a set of models:

当然,您也可以对一组模型运行删除查询:

$affectedRows = User::where('votes', '>', 100)->delete();

More info: http://laravel.com/docs/eloquent

更多信息:http: //laravel.com/docs/eloquent