我已将博客中所有帖子的集合发送到我的索引视图,然后使用以下代码计算每个用户发布的总帖子。
<p class="joined-text">Posts: {{count(App\Posts::where('user_id', $post->user->id)->get())}}</p>
这种不良做法是否在刀片视图中执行此操作?如果是我将如何实现这一目标?
模型
class Posts extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
public function comments()
{
return $this->hasMany(Comments::class, 'post_id');
}
}
class User extends Authenticatable
{
public function posts()
{
return $this->hasMany('\App\Posts::class');
}
public function comments()
{
return $this->hasMany(Comments::class);
}
}
答案 0 :(得分:1)
简单的解决方案:
<p class="joined-text">Posts: {{ App\Posts::where('user_id', $post->user_id)->count() }}</p>
<强>更新强>
完整且更好的解决方案:
Post.php
:
public function user(){
return $this->belongsTo(App\User::class);
}
User.php
:
public function posts(){
return $this->hasMany(App\Post::class);
}
public function getPostsCountAttribute(){
return $this->posts()->count();
}
刀片:
<p class="joined-text">Posts: {{ $post->user->posts_count }}</p>
答案 1 :(得分:0)
是的,这很糟糕。
如果user_id
表中有posts
字段
class User extends Model
{
public function posts()
{
return $this->hasMany('App\Post');
}
}
在控制器中
return view('sth')->with(['posts'=>$user->posts]);
然后在视图中
$posts->count();
如果您不需要帖子,只需获取计数
$postCount = $user->posts()->count();