作为程序员一定要保持良好的睡眠,才能好编程

laravel关联模型之关联模型计数

发布时间:2020-01-29


关联模型之关联数量计数


https://learnku.com/docs/laravel/6.x/eloquent-relationships/5177#cc241a



关联模型中 关联计数

withCount() 这个方法


当使用withCount方法后,获取到的参数都是  *_count


比如:withCount('user')  则 获取到的是 user_count 


例如:

$posts = App\Post::withCount('comments')->get();
foreach ($posts as $post) {
    echo $post->comments_count;
}


use Illuminate\Database\Eloquent\Builder;

$posts = App\Post::withCount(['votes', 'comments' => function (Builder $query) {
    $query->where('content', 'like', 'foo%');
}])->get();

echo $posts[0]->votes_count;
echo $posts[0]->comments_count;



还可以使用 as 方法 起一个别名

use Illuminate\Database\Eloquent\Builder;

$posts = App\Post::withCount([
    'comments',
    'comments as pending_comments_count' => function (Builder $query) {
        $query->where('approved', false);
    },
])->get();

echo $posts[0]->comments_count;

echo $posts[0]->pending_comments_count;