我想创建类似 SQL 子查询别名的东西,这样我就可以像普通 SQL 字段一样使用它。例如,我有 3 个表:user
、user_comments
和 user_comment_answers
。如果我想统计当前用户评论的所有答案,我会这样做:
SELECT
COUNT(*) as comment_answers_count
FROM user_comment_answers
WHERE user_comment_id IN (SELECT id FROM user_comments WHERE user_id = :id)
现在我想让 Laravel 将其视为 user
表的一个普通字段,所以我可以简单地做这样的事情:
echo Auth::user()->comment_answer_count
或者像这样
$popularUsers = User::where('comment_answer_count', '>=', 100)
如何在 Laravel 5.4 中实现这一点?
最佳答案
尝试
$users = Auth::withCount('comments')->get();
现在所有用户都有一个comments_count
属性
foreach($users as $user) {
echo $user->comments_count;
}
假设您在 User
和 Comment
模型中定义了关系。
更新
根据你的第一条评论,你想要的是一个accessor
public function getCommentAnswerCountAttribute($value) {
//define your query here
}
更多信息在这里:https://laravel.com/docs/5.4/eloquent-mutators#defining-an-accessor
希望这能给你找到解决方案的提示
关于mysql - 创建一个子查询别名以在 Laravel 查询生成器中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42197944/