Did you try DB:: raw ()?
The COUNT Function in SELECT statement
Hello,
i have two tables named "article" and "comment". So, i want to select some information about all articles and the comment's count for each article especially.
The SQL-Code i used bevor looks like that:
SELECT article . * , COUNT( comment.article_id ) AS commentsCount
FROM `article`
LEFT JOIN comment ON article.id = comment.article_id
GROUP BY article.id
ORDER BY article.id DESC
LIMIT 0 , 30
My problem is that i can't get it to work with Eloquent. I tried
$info = Article::select
( // Article's ID
'article.id',
// Article's Title
'article.title',
// ID of Article's Category
'article.category_id as cid',
// Author's ID
'article.user_id as uid',
// Summary count of all Views
'article.views',
// Creation's Time
'article.created_at',
// Author's Nickname
'user.username',
// Comment's Count
// 'count(comment.article_id) as count' <-- Doesn't WORK, I know! but i tries Comment::raw('count(comment.article_id)') too
)
->leftJoin('user', 'user.id', '=', 'article.user_id')
->leftJoin('comment', 'article.id', '=', 'comment.article_id')
->groupBy('article.id')
->orderBy('article.id', 'desc')->get()
));
So, how can I get the count of all comments for each article?
@harryg Yes, of course, I can use the Eloquent's name convention, but i'm using the ER-Model and let my table's names always be in singular
protected $table = 'comment';
// with the primary key = id
// and
// with the foreign keys like foreign_table_id
the problem was that Eloquent interpreted
'count(comment.article_id) as count'
like a column name and not like a statement. Furthermore there is no DB::raw() in Eloquent Standalone (or i haven't found it), but i have been advised of possibility to use in my case
new Illuminate\Database\Query\Expression('count(comment.article_id) as answers')
instead of DB::raw()
P.S. Thank you for your advice
Please or to participate in this conversation.