gpt4 book ai didi

Laravel - Collection::delete 方法不存在

转载 作者:行者123 更新时间:2023-12-05 08:20:04 30 4
gpt4 key购买 nike

我正在尝试测试 boot() static::deleting 方法,该方法应该在通过 Eloquent 删除模型时触发。

tinker App\User::find(6)->delete(); 中的命令返回“方法 [...]Collection::delete 不存在”。

如果我尝试使用 App\User::where('id', 6)->delete(); 那么 static::deleting 方法不会被触发,因为没有加载 Eloquent .如果我用 ->first() 加载 Eloquent,那么我会得到同样的错误,指出方法不存在。

这是整个用户模型

 <?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',
];
}

我现在已经花了几个小时在谷歌上寻找可能的解决方案,但还没有找到。

如何在触发引导删除方法时正确删除用户模型?

最佳答案

在您的 deleting 监听器中,您正试图删除其他内容,这是导致错误的集合。

$user->posts 是与 Posts 的关系,它是一个复数形式,是一个 hasMany 关系(最有可能),因此它返回一个 Collection always。集合没有 delete 方法。您将必须遍历集合并在每个帖子上调用 delete

// calling `delete()` on a Collection not a Model
// will throw the error you see
$user->posts->delete();

// iterate through the Collection
foreach ($user->posts as $post) {
$post->delete();
}

旁注:您不能对模型和查询批量执行任何操作,也不能触发事件。所有模型事件都基于模型的单个实例。直接查询绕过模型。

关于Laravel - Collection::delete 方法不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62695966/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com