dongyi0114 2017-09-03 17:18
浏览 37
已采纳

在laravel 5问题中使用软删除

This is my model:

namespace App\Models\Admin;

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

class Image extends Model
{
    use SoftDeletes;
    //table
    protected $table = 'images';
}

If I add my trait I cannot find any record if I use my model like this:

$imageFile = ImageModel::where('id', 12)->first();

The $imageFile is always null, if I remove my trait is working . Why ???

  • 写回答

1条回答 默认 最新

  • dongyuan3094 2017-09-03 18:32
    关注

    From what you've said, it is working as intended. When you use the soft-delete trait in Laravel, the model is NOT deleted from the DB. When you pass the model to destroy(), the only thing that happens is that the deleted_at field becomes non-null.

    If you look deeper into Laravel's code, when you call

    ImageModel::where('id', 12)->first(); 
    

    the softdelete trait is adding

    where null
    

    to the SQL for the deleted_at column. This means that, as you said, if you turn off the trait, $imageFile will not be null (it is working). Because the softdelete never deleted the model from the DB - it just added a non-null value to the DB for that model and is thus visible to a normal laravel query: when you don't use softdeletes, Laravel doesn't care about the deleted_at field so it sees the model. When you turn softdeletes on, it looks for null values only, and because your model was softdeleted (it has a non-null value), it returns $imageFile as null.

    As bytewave said, to properly use the softdeletes to NOT return a null value to $imageFile, you would need to add in the softdeleted models to your query like so:

    Image::withTrashed()->where('id', 12')->first();
    

    I think you were looking for slightly different functionality (a roll-back), which is a little different from the softdelete trait's intention. The manual is pretty good: 5.4 soft-deletes, but looking deeper into the trait code might help as well.

    Take a look at the ->restore() function as well - this might help you get closer to the intended roll-back you were looking for. But, you need the logic up-front first to know which were deleted.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值