【发布时间】: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