Laravel-Collection :: delete方法不存在 [英] Laravel - Collection::delete method does not exist

查看:71
本文介绍了Laravel-Collection :: delete方法不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to test the boot() static::deleting method, which should fire when a model is deleted through Eloquent.

修补程序 App \ User :: find(6)-> delete(); 中的命令返回方法[...] Collection :: delete不存在".

The command in tinker App\User::find(6)->delete(); returns a 'method [...]Collection::delete does not exist'.

如果我尝试使用 App \ User :: where('id',6)-> delete(); ,则不会触发static :: deleting方法,因为Eloquent不是已加载.如果我用-> first()加载Eloquent,那么我会得到一个错误,指出方法不存在.

If I try to use App\User::where('id', 6)->delete(); then the static::deleting method does not get triggered since Eloquent is not loaded. If I load Eloquent with ->first() then I get the same error that states method does not exist.

这是整个用户模型

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

我现在已经花了几个小时在Google上寻找可能的解决方案,但目前还没有.

I have spent hours now looking through google for possible solutions but nothing has yet.

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

How should I properly delete a User model while triggering the boot deleting method ?

推荐答案

在您的删除侦听器中,您试图删除其他内容,这是导致错误的Collection.

In your deleting listener you are trying to delete something else, which is a Collection which is causing the error.

$ user-> posts 是与Posts的关系,Posts是具有hasMany关系(最有可能)的复数形式,因此它会返回始终.集合没有 delete 方法.您将不得不遍历整个集合并在每个帖子上调用 delete (删除)

$user->posts is a relationship to Posts which is a plural which is a hasMany relationship (most likely) so it returns a Collection always. Collections do not have a delete method. You will have to iterate through the collection and call delete on each Post

// 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();
}

侧面注意:您无法对模型和查询进行任何批量操作,并且会触发事件.所有模型事件均基于模型的单个实例.直接查询会绕过模型.

Side Note: you can not do any action in bulk with Models and queries and have the events be fired. All Model events are based on single instances of the Models. A direct query bypasses the Model.

这篇关于Laravel-Collection :: delete方法不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆