这是文档里说的:

Deleting An Existing Model By Key
In the example above, we are retrieving the model from the database before calling the delete method. However, if you know the primary key of the model, you may delete the model without retrieving it. To do so, call the destroy method:

  App\Flight::destroy(1);
  App\Flight::destroy([1, 2, 3]);
  App\Flight::destroy(1, 2, 3);

那么,这个destroy的返回值是什么呢?怎样判断是否删除成功了呢?

其实根据源代码,这个destroy方法也是调用了delete方法。
具体实现是这样的:

public static function destroy($ids)
    {
        $count = 0;
        $ids = is_array($ids) ? $ids : func_get_args();
        $key = ($instance = new static)->getKeyName();
        foreach ($instance->whereIn($key, $ids)->get() as $model) {
            if ($model->delete()) {
                $count++;
            }
        }
        return $count;
    }

可以看到,其实是首先设置了一个$count,初始化为0,如果删除成功,就$count++
所以比如你删3个,就返回3。

标签: model, eloquent, destroy

添加新评论