//我收到以下错误: Builder.php第2345行中的错误异常:调用未定义的方法Illuminate \ Database \ Query \ Builder :: replies()(查看:d:\ xampp \ htdocs \ myproject \ resources \ views \ homepost.blade.php)
//我试图在视图中查看(已批准的回复),但这不适用于我!!
在视图中:
@if($posts)
@foreach($posts as$post)
<p>No. approved replies={{$post->comments()->replies()->whereIsActive(1)->count()}}</p>
<p>No. category={{$post->category()->count()}}
@endforeach
@endif
在Post控制器中:
public function index()
{
$posts=Post::all();
return view('Admin.posts.index',compact('posts'));
}
在Post模型中:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable=[
'title','body','category_id','photo_id'
];
public function user(){
return $this->belongsTo('App\User');
}
public function category(){
return $this->belongsTo('App\Category');
}
public function comments(){
return $this->hasMany('App\Comment');
}
}
在评论模型中:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $fillable=[
'post_id',
'photo',
'author',
'email',
'body',
'is_active'
];
public function replies(){
return $this->hasMany('App\CommentReply');
}
public function post(){
return $this->belongsTo('App\Post');
}
}
在CommentReply模型中:
namespace App;
use Illuminate\Database\Eloquent\Model;
class CommentReply extends Model
{
protected $fillable=[
'comment_id',
'is_active',
'author',
'photo',
'email',
'body'
];
public function comment(){
return $this->belongsTo('App\Comment');
}
}
答案 0 :(得分:0)
尝试一下:
$post->comments()
->join(DB::raw('(Select comment_id,count(*) as total from CommentReply where is_active = 1 group By comment_id) as replies'),function($join){
$join->on('comments.id', '=', 'replies.comment_id')
})
->selectRaw('sum(replies.total) as total_comments')
->get('total_comments');