【问题标题】:Deleting a comment and associated images删除评论和相关图像
【发布时间】:2018-02-22 06:30:11
【问题描述】:

我正在尝试通过从数据库记录和存储中删除单个用户 cmets 和与它们相关的图片来删除它们。不幸的是,我不断收到错误。以下是我到目前为止的代码。

表: 评论:id、评论、user_id、person_id 图片:id、图片、comment_id、user_id、person_id

关系: 评论:

public function pictures()
{
    return $this->hasMany('App\Picture', 'comments_id', 'id');
} 

图片:

   public function comments()
    {
        return $this->belongsTo('App\Comment', 'comments_id');
    }

控制器:

public function destroy($id)
{
    $comment = Comment::find($id);
    Storage::delete($comment->pictures());

    $comment->delete();
    Session::flash('success', 'Your comment and pictures were deleted');

    return redirect()->route('home');
} 

有什么想法吗?

【问题讨论】:

  • 错误是什么??
  • 它不会同时删除评论和相关图片。

标签: php laravel laravel-5 eloquent laravel-5.5


【解决方案1】:

你需要使用pluck()来加载图片文件名:

$files = $comment->pictures()->pluck('filename');

然后删除这些文件:

foreach ($files as $file) {
    Storage::delete(storage_path('images/' . $file));
}

这只是一个示例,您需要输入正确的列名而不是 filename 并构建正确的图像路径。

从数据库中删除图像:

$comment->images()->delete();

【讨论】:

    【解决方案2】:

    $comment->pictures() 返回关系的定义,而不是相关的图片。如果要删除所有图片,则需要遍历它们并逐一删除:

    $comment = Comment::find($id);
    foreach ($comment->pictures as $picture) {
      // delete picture from storage
      Storage::delete($picture->id); //or whatever field is used as key in the storage
      // delete picture from the database - might be optional if you've set a cascade on delete behaviour in your foreign key definition
      $picture->delete();
    }
    

    【讨论】:

      【解决方案3】:

      您需要提供图片的filename 才能从storage 中删除图片。

      $comment = Comment::find($id);
      foreach($comment->pictures as $picture)
              Storage::delete($picture->image);
      
      Picture::where('comment_id',$comment->id)->delete();
      $comment->delete();
      

      【讨论】:

        猜你喜欢
        • 2014-08-02
        • 2017-11-19
        • 1970-01-01
        • 2019-08-29
        • 1970-01-01
        • 2021-05-01
        • 1970-01-01
        • 2011-12-18
        • 2019-08-30
        相关资源
        最近更新 更多