Почему удаление строки в связанной строке boot () не запускается? - PullRequest
0 голосов
/ 29 октября 2018

В моем приложении Laravel 5.7 у меня есть 2 таблицы Tag, TagDetail (отношение один к одному), а во второй таблице изображение загружено в хранилище и поле изображения. Я хочу использовать загрузочный метод для автоматического удаления связанных строк и изображений. В результате удаления строки Tag, связанной с TagDetail, удаляется, но изображение TagDetail не удаляется У меня есть 2 модели и новый тег ()) -> D (это просто функция отладки app / Tag.php:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

use DB;
use App\MyAppModel;
use App\TagDetail;
use App\Http\Traits\funcsTrait;
use Illuminate\Validation\Rule;
use App\Rules\TagUniqueness;


class Tag extends MyAppModel
{
    use funcsTrait;

    protected $table = 'tags';

    protected $primaryKey = 'id';
    public $timestamps = false;
    private $votes_tag_type= 'votesTagType';

    public function getTableName() : string
    {
        return $this->table;
    }

    public function getPrimaryKey() : string
    {
        return $this->primaryKey;
    }

    public function tagDetail()
    {
        return $this->hasOne('App\TagDetail', 'tag_id', 'id');
    }

    protected static function boot() {
        parent::boot();
        static::deleting(function($tag) {
            with (new Tag())->d( '<pre>Tag BOOT $tag::' . $tag->id);
            $relatedTagDetail= $tag->tagDetail();
            if ( !empty($relatedTagDetail) ) {
                $relatedTagDetail->delete();  // I see this is triggered and  relatedTagDetail is deleted 
            }
        });
    }

и app / TagDetail.php:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use DB;
use App\MyAppModel;
use App\library\ImagePreviewSize;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use App\Http\Traits\funcsTrait;

class TagDetail extends MyAppModel
{
    use Notifiable;
    use funcsTrait;

    protected $table = 'tag_details';
    protected $primaryKey = 'id';
    public $timestamps = false;

    protected $fillable = [
        'tag_id',
        'image',
        'description',
    ];

    public function getTableName() : string
    {
        return $this->table;
    }

    public function getPrimaryKey() : string
    {
        return $this->primaryKey;
    }

    public function Tag()
    {
        return $this->belongsTo('App\Tag', 'tag_id');
    }


    protected static function boot() {
        parent::boot();
        static::deleting(function($tagDetail) { // THIS METHOD IS NOT TRIGGERED AT ALL!
            with (new TagDetail())->d( '<pre>TagDetail BOOT $tagDetail::' . $tagDetail->id);

            $tag_detail_image_path= TagDetail::getTagDetailImagePath($tagDetail->id, $tagDetail->image, true);
            with (new TagDetail())->d( '<pre>TagDetail BOOT $tag_detail_image_path::' . $tag_detail_image_path);
            TagDetail::deleteFileByPath($tag_detail_image_path, true);
        });
    }

Что-то не так в моих объявлениях моделей?

МОДИФИЦИРОВАННЫЙ БЛОК № 2: В моем включенном файле public / js / defaultBS41Backend / admin / tag.js у меня есть метод:

backendTag.prototype.deleteTag = function (id, name) {
    confirmMsg('Do you want to delete "' + name + '" tag with all related data ?', function () {
            var href = this_backend_home_url + "/admin/tag/destroy";

            $.ajax({
                type: "DELETE",
                dataType: "json",
                url: href,
                data: {"id": id, "_token": this_csrf_token},
                success: function (response) {
                    $("#btn_run_search").click()
                },
                error: function (error) {
                    alertMsg(error.responseJSON.message, 'Tag deleting error!', 'OK', 'fa fa-exclamation-triangle')
                }
            });

        }
    );

} // backendTag.prototype.deleteTag = function ( id, name ) {

и в управлении:

public function destroy(Request $request)
{
    $id  = $request->get('id');
    $tag = MyTag::find($id);

    if ($tag == null) {
        return response()->json(['error_code' => 11, 'message' => 'Tag # "' . $id . '" not found!', 'tag' => null],
            HTTP_RESPONSE_INTERNAL_SERVER_ERROR); //500
    }

    DB::beginTransaction();
    try {
        $tag->delete();
        DB::commit();

    } catch (Exception $e) {
        DB::rollBack();

        return response()->json(['error_code' => 1, 'message' => $e->getMessage(), 'tag' => null], HTTP_RESPONSE_INTERNAL_SERVER_ERROR);
    }

    return response()->json(['error_code' => 0, 'message' => ''], HTTP_RESPONSE_OK_RESOURCE_DELETED); // 204
} //     public function delete(Request $request)

и в маршрутах / web.php:

Route::group(['middleware' => ['auth', 'isVerified'], 'prefix' => 'admin', 'as' => 'admin.'], function () {
    Route::delete('/tag/destroy', 'Admin\TagsController@destroy');
    ...

1 Ответ

0 голосов
/ 30 октября 2018

Проблема: $tag->tagDetail(): вы используете построитель запросов и удаляете модель непосредственно в базе данных. Но событие deleting может быть инициировано только при первом получении модели.

Заменить $relatedTagDetail = $tag->tagDetail(); на $relatedTagDetail= $tag->tagDetail;.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...