我有一个使用软删除的模型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')
添加到->hasMany('Comment')
和->belongsTo('Post')
,但没有运气。
我已经检查了数据库并运行了SQL,我希望Fluent和Eloquent能够生成
SELECT * FROM `comments` WHERE post_id=31 and deleted_at=null
(31是我用来测试的帖子)。什么都行不通。如果你们需要看到更具体的功能,请告诉我,因为我不想发布我的整个模型。
答案 0 :(得分:2)
我能够使其与->whereRaw('deleted_at = ?',array(NULL))
一起使用。这对我来说似乎很不好看。我很乐意接受更好的答案。
答案 1 :(得分:2)
将您的代码更改为:
return \App\Comments::count();
软删除仅适用于模型,不适用于查询:
class Comment extends Eloquent
{
protected $softDelete = true;
}
答案 2 :(得分:1)
您必须在模型中启用软删除。
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();
}
答案 3 :(得分:0)
尽管这是一篇老文章,但如果其他人遇到此问题,希望对其他人有帮助。
对于laravel V5及更高版本。
将use SoftDeletes;
添加到模型中。
如果您要获取包含软删除的计数,请使用以下内容:
Model::withTrashed()->'yourquery'
如果您不希望包含软删除的记录,则可以按照常规对流进行。
Model::select()->get();