2

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

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

我已经让 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')到 the->hasMany('Comment')和 the 中->belongsTo('Post'),但没有成功。

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

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

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

4

4 回答 4

2

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

于 2014-01-10T21:57:46.500 回答
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();
}
于 2014-01-10T23:35:29.430 回答
2

将您的代码更改为:

return \App\Comments::count();

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

class Comment extends Eloquent
{
    protected $softDelete = true;

}
于 2015-11-04T16:10:34.833 回答
1

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

对于 laravel V5 及以上版本。

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

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

Model::withTrashed()->'yourquery'

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

Model::select()->get(); 
于 2020-02-28T09:30:48.610 回答