【问题标题】:soft deleted in laravel 5 apply physicaldelete not set deleted_at在 laravel 5 中软删除应用物理删除未设置已删除_at
【发布时间】:2015-04-25 17:01:29
【问题描述】:

我的模型是:

<?php namespace App\Http\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Province extends Model {

 // use SoftDeletes;

public $timestamps = false;

protected $dates = ['deleted_at'];

public function country(){
    return $this->belongsTo('App\Http\Models\Country');
}

public function users(){
    return $this->hasMany('App\Http\Models\User');
}

public function customers(){
    return $this->hasMany('App\Http\Models\Customer');
}

}

控制器:

public function destroy($id)
{
    $province = Province::with('country')->where('id', $id)->first();

   // dd($province);
    $province->delete();
 }

拨打http://localhost:8080/pal/public/province/22/delete时。

记录 22 从数据库中物理删除。

缺少什么?

【问题讨论】:

  • 你已经注释掉了use SoftDeletes
  • 因为在未注释时我收到此错误:调用非对象上的成员函数 delete()
  • 是的,可能是因为它已经被软删除并且first() 返回null
  • 我怎么知道它是否被软删除它的 delete_at = 4/25/2015 11:44:48 AM
  • 然后是软删除。手动将值设置为null 以“取消删除”

标签: laravel laravel-4 laravel-5


【解决方案1】:

当您的模型启用软删除时,当您进行查询时,不会返回 deleted_at 不是 null 的记录。因此,您尝试在 null 上调用 delete(),这会导致错误。

手动将 deleted_at 设置为 null 以在测试期间“取消删除”记录。

此外,您可能应该在删除之前检查模型是否为null

$province = Province::with('country')->where('id', $id)->first();

if($province != null){
    $province->delete();
}

【讨论】:

  • 没有if: Province::with('country')-&gt;where('id', $id)-&gt;firstOrFail()-&gt;delete();
  • @limonte Province::with('country')-&gt;findOrFail($id)-&gt;delete() ;)
  • 跟我想的完全一样! :)
猜你喜欢
  • 2016-03-05
  • 1970-01-01
  • 2015-10-06
  • 1970-01-01
  • 2022-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多