這是我的博文模型。類型鑄造laravel json響應關係渴望加載
class Post extends Model
{
use SoftDeletes;
protected $table = 'posts';
protected $fillable = ['title','featuring_image', 'brief', 'body', 'seen_count'];
public function user(){
return $this->belongsTo(User::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
public function someComments()
{
return $this->comments()->limit(Constants::COMMENTS_COUNT_LIMIT);
}
public function commentsCount()
{
return $this->comments()
->selectRaw('post_id, count(*) as count')
->groupBy('post_id');
}
public function likes()
{
return $this->hasMany(Like::class);
}
public function isLiked()
{
return $this->likes()->where('user_id', auth()->check() ? auth()->user()->id : 0);
}
public function likesCount()
{
return $this->likes()
->selectRaw('post_id, count(*) as count')
->groupBy('post_id');
}
}
我在這個模型上執行了這個查詢。
$post = Post::with(['categories', 'user', 'commentsCount', 'likesCount', 'isLiked'])->find($post->id);
因爲此表和像和評論表之間的關係的,該查詢的用於'commentsCount', 'likesCount', 'isLiked'
的輸出是一個數組。但是我需要在laravel josn響應中接收'commentsCount'
和'likesCount'
的數字,以及作爲輸出的'isliked'
的布爾值。
您正在使用什麼版本的Laravel的? –
@RossWilson \t laravel v5.4.35 – AHS441