Ich habe keine Idee, wie man dieses Problem mit Laravel Eloquent löst. Also, ich habe meine Frage hier gepostet.
Ich habe Tabellen wie folgt aus:Eloquent: Zählen Sie Zeilenbasis auf Tabellenrelation
+-------------+ +------------------------+
| POSTS | | COMMENTS |
|-------------| |------------------------|
| id | title | | id | text | post_id |
|-----+-------| |----+-------------------|
| 1 | A | | 1 | Lorem | 1 |
| 2 | B | | 2 | Ipsum | 1 |
+-------------+ | 3 | Dolor | 1 |
| 4 | Sit | 1 |
| 5 | Amet | 2 |
| 6 | Lorem 2 | 2 |
+------------------------+
Ich habe derzeit zwei Modelle, Post Modell
class Post extends Model
{
public function comment() {
$this->hasMany('App\Comment');
}
}
und Kommentieren Modell
class Comment extends Model
{
public function comment() {
$this->belongsTo('App\Post');
}
}
Die Frage ist, was soll ich auf tun der Controller, damit ich jedem Beitrag eine Kommentaranzahl geben kann? Oder einfach, genau wie die Tabelle unten.
+-----------------------------------------+
| COMMENT COUNT |
|-----------------------------------------|
| posts.id | count(comments.post_id) AS n |
|----------+------------------------------|
| 1 | 4 |
| 2 | 2 |
+-----------------------------------------+
Danke.
Haben Sie die Tabelle Comment Count erstellt? –