【问题标题】:count() returning soft deleted items in laravelcount() 在 laravel 中返​​回软删除的项目
【发布时间】:2014-01-30 00:45:00
【问题描述】:

我有一个使用软删除的模型Comments:它与我的Post 模型有one-to-many 关系。

我的网站将有一个与之关联的本机移动应用程序,当我发送有关帖子的信息时,我需要向它发送 cmets 的计数,并且由于某种原因它会返回带有软删除项目的计数。

我已经让 Post 数组正常工作并使用

发送评论计数
protected $appends = array('score','commentcount', 'ups', 'downs');

public function getCommentcountAttribute()
{    
     return DB::table('comments')
         ->where('post_id',$this->id)
         ->where('deleted_at','=',NULL)
         ->count();    
}

在我的帖子模型中。我也试过了

public function getCommentcountAttribute()
{
    return $this->comments()->count();
}

public function getCommentcountAttribute()
{   
    return $this->comments()->whereNull('deleted_at')->count();
    // also: return $this->comments()->where('deleted_at',NULL)->count();
}

在定义关系时,我尝试将->whereNUll('deleted_at') 添加到->hasMany('Comment')->belongsTo('Post'),但没有成功。

我检查了数据库并运行了我期望 Fluent 和 Eloquent 生成的 SQL

SELECT * FROM `comments` WHERE post_id=31 and deleted_at=null

(31 是我用来测试的帖子)。没有任何工作。让我知道你们是否需要查看更多特定功能,因为我不想发布我的整个模型。

【问题讨论】:

    标签: php laravel eloquent fluent soft-delete


    【解决方案1】:

    我能够使它与->whereRaw('deleted_at = ?',array(NULL)) 一起工作。不过,这对我来说似乎很hacky。我很乐意接受更好的答案。

    【讨论】:

      【解决方案2】:

      您必须在模型中启用软删除。

      class Comment extends Eloquent {
      
          protected $softDelete = true;
      
      }
      

      就是这样。

      而且您不需要在查询中包含以下 where 子句:

      return DB::table('comments')
               ->where('post_id',$this->id)
               //->where('deleted_at','=',NULL) // no needed, Laravel by default will include this condition
               ->count();   
      
      
      public function getCommentcountAttribute()
      {   
         // remove  ->whereNull('deleted_at')
         return $this->comments()->count();
      }
      

      【讨论】:

      • 应该包括我已经这样做了。除了我使用 ->toArray()count() 时,软删除无处不在。
      【解决方案3】:

      将您的代码更改为:

      return \App\Comments::count();
      

      软删除仅适用于模型,不适用于查询:

      class Comment extends Eloquent
      {
          protected $softDelete = true;
      
      }
      

      【讨论】:

        【解决方案4】:

        虽然这是一篇旧帖子,但如果遇到此问题,希望以下内容对其他人有所帮助。

        适用于 laravel V5 及以上版本。

        use SoftDeletes; 添加到您的模型中。

        如果您尝试获取包含软删除的计数,请使用以下命令:

        Model::withTrashed()->'yourquery'
        

        如果您不希望包含软删除记录,则可以按照正常对流进行。

        Model::select()->get(); 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-07-29
          • 1970-01-01
          • 2016-07-24
          • 1970-01-01
          • 2014-05-31
          相关资源
          最近更新 更多