我使用的是Laravel 5.4。
我将软删除添加到用户模型。
赞use SoftDeletes
和$dates = ['deleted_at']
当我使用User::destroy(1)
时,它实际上会在数据库中添加deleted_at值,所以我确定没有关于SoftDeletes的设置问题。
但是当我获得用户列表并使用用户模型登录时,它不会过滤删除的行。
有没有人有同样的问题?请告诉我你是如何解决的。
- 更新 -
应用\ user.php的
<?php
namespace App;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
use Laravel\Scout\Searchable;
class User extends Authenticatable
{
/**
* Added for passport - api login checking
*/
use HasApiTokens, Notifiable, Searchable;
use SoftDeletes;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
];
protected $dates = [
'created_at',
'updated_at',
'deleted_at',
];
}
UserController.php
<?php
namespace App\Http\Controllers;
use App\Events\ErrorLog;
use App\Helpers;
use App\Http\Controllers\Controller;
use App\User;
use Validator;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$fields = $request->fields ? $request->fields :
[
'id',
'name',
'email',
];
$search = function ($query) {
$query->where('name', 'like', '%' . request()->nameOrEmail . '%')
->orWhere('email', 'like', '%' . request()->nameOrEmail . '%');
};
$users = User::where($search)
->orderBy('id')
->paginate(20, $fields);
return response()->json([
'status' => 'success',
'data' => $users,
]);
}
}
答案 0 :(得分:5)
软删除过滤器仅适用于雄辩的ORM
如果您不使用eloquent,即使用查询构建器或某些原始sql,则需要手动检查软删除
例如
$user= User::all(); //eloquent
与
相同 SELECT
*
FROM
users
WHERE
deleted_at IS NULL
但不适用于
$users=DB::table('users') //non eloquent
只是
SELECT * FROM users
在这种情况下,您需要传递一些条件
DB::table('users')
->whereNull('deleted_at');
修改
您使用了覆盖雄辩条件的查询构建器,请尝试以下
$users = User::where($search)
->whereNull('deleted_at')
->orderBy('id')
->paginate(20, $fields);