【发布时间】:2020-07-02 12:05:49
【问题描述】:
我正在尝试测试 boot() static::deleting 方法,该方法应在通过 Eloquent 删除模型时触发。
tinker App\User::find(6)->delete(); 中的命令返回“方法 [...]Collection::delete 不存在”。
如果我尝试使用App\User::where('id', 6)->delete();,那么由于未加载 Eloquent,因此不会触发 static::deleting 方法。如果我用->first() 加载 Eloquent,那么我会得到相同的错误,即 states 方法不存在。
这是整个用户模型
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
public function profile() {
return $this->hasOne(Profile::class);
}
public function posts() {
return $this->hasMany(Post::class);
}
public function tempUploads() {
return $this->hasMany(TempUploads::class);
}
protected static function boot() {
parent::boot();
static::created(function ($user) {
$user->profile()->create(['id' => $user->username, 'avatar' => '/storage/avatars/edit-profile.png']);
mkdir(public_path() . "/storage/images/" . $user->username , 0755);
// $data = [
// 'user_id' => $user->username
// ];
// Mail::to($user->email)->send(new WelcomeMail($data));
});
static::deleting(function ($user) {
$user->posts->delete();
if ($user->profile->avatar != '/storage/avatars/edit-profile.png') {
if ($user->profile->cover != NULL && $user->profile->cover != '') {
$oldAvatar = $_SERVER['DOCUMENT_ROOT'] . $user->profile->avatar;
$oldCover = $_SERVER['DOCUMENT_ROOT'] . $user->profile->cover;
if (is_file($oldAvatar) && is_file($oldCover)) {
unlink($oldAvatar);
unlink($oldCover);
} else {
die("Грешка при изтриване на стария файл. File does not exist in profile deleting method.");
}
}
}
$user->profile->delete();
});
}
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'username', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
我现在已经花了几个小时在谷歌上寻找可能的解决方案,但还没有。
在触发启动删除方法时我应该如何正确删除用户模型?
【问题讨论】:
-
如果你已经定义了监听器,你可以粘贴那个代码
-
对不起,我不太清楚你的建议是什么,你能改写一下吗?
-
find应该只返回一个集合,如果你向它传递一个数组.. 否则你应该得到一个模型实例或 null 并且应该能够在模型实例上调用delete/跨度> -
delete()只能在QueryBuilder实例See here 上调用 -
@user3647971 我应该使用什么方法来删除模型以触发删除方法?
标签: laravel