laravel自定义软删除问题
一.自定义一个SoftDeletes
<?php
namespace lib\laravel\orm;
trait SoftDeletes
{
use \Illuminate\Database\Eloquent\SoftDeletes;
public static function bootSoftDeletes()
{
static::addGlobalScope(new SoftDeletingScope);
}
public function getDeletedAtColumn()
{
return 'is_del';
}
}
2.重写一个SoftDeletingScope
<?php
namespace lib\laravel\orm;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
class SoftDeletingScope extends \Illuminate\Database\Eloquent\SoftDeletingScope
{
/**
* 将范围应用于给定的 Eloquent 查询构建器。
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function apply(Builder $builder, Model $model)
{
$builder->where('is_del', '=', 0);
}
public function extend(Builder $builder)
{
foreach ($this->extensions as $extension) {
$this->{"add{$extension}"}($builder);
}
$builder->onDelete(function (Builder $builder) {
$column = $this->getDeletedAtColumn($builder);
return $builder->update([
$column => 1,
]);
});
}
}
3.使用
<?php
namespace plugin\admin\app\model;
use lib\laravel\orm\SoftDeletes;
use plugin\admin\app\model\Base;
/**
* @property integer $id (主键)
* @property string $title 名称
* @property string $icon 图标
* @property integer $pid 上级
* @property integer $status 状态 1启用 2禁用
* @property integer $sort 排序
* @property string $created_at
* @property string $updated_at
* @property integer $is_del 1删除
*/
class BlogCategory extends Base
{
use SoftDeletes;
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'blog_category';
/**
* The primary key associated with the table.
*
* @var string
*/
protected $primaryKey = 'id';
}
- 查询出来的结果
{ "code": 0, "data": [ { "id": 1, "title": "1111", "icon": "", "pid": 0, "status": 1, "sort": 0, "created_at": "2024-04-07 17:00:11", "updated_at": "2024-04-07 17:22:37", "is_del": "1970-01-01 08:00:00", "name": "1111", "value": 1 } ], "msg": "ok" }
问题是:is_del这个数据被格式为了1970-01-01 08:00:00,数据库存的是0,有谁知道laravel是在哪个类中格式化的这个时间吗或者是该怎样让查出的数据不格式化
看 源码 就知道了,定义一个空的
initializeSoftDeletes
方法在你的 trait 就好了或者手动设置一下 casts 为 int