What is the difference between destroy() and delet

2019-02-02 20:00发布

问题:

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?

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

回答1:

  • destroy is correct method for removing an entity directly (via object or model).

Example:

$teetime = Teetime::where('date', '=', $formattedDate)->firstOrFail();
$teetime->destroy();
  • delete can only be called in query builder

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