mardi 19 janvier 2016

Relationship between 4 tables Laravel 5.1

I need to show feeds with total comments, and total likes on that feed with the detail of users who have commented.

Feeds Table

| id | movie_id | user_id  | description | 
|----|----------|----------|-------------|
| 1  | 1        | 1        | Lorem Ipsum |

Comments Table

| id | feed_id | user_id  | comment   | 
|----|-------- |----------|-----------|
| 1  | 1       | 2        | comment 1 |
| 2  | 1       | 3        | comment 2 |

Likes Table

| id | feed_id | user_id  |
|----|-------- |----------|
| 1  | 1       | 2        |
| 2  | 1       | 3        |

Users Table

| id | username| email  |
|----|-------- |--------|
| 1  | a       | a@a.com|
| 2  | b       | b@b.com|
| 3  | c       | c@c.com|

Relations

Feed.php

public function user () {
    return $this->belongsTo('App\User');
}

public function likes () {
    return $this->hasMany('App\Like');
}

public function comments () {
    return $this->hasMany('App\Comment');
}

User.php

public function feeds () {
    return $this->belongsToMany('App\Feed');
}

public function like () {
    return $this->belongsTo('App\Like');
}

public function comment () {
    return $this->belongsTo('App\Comment');
}

Like.php

public function user () {
    return $this->belongsTo('App\User');
}

public function feed () {
    return $this->belongsTo('App\Feed');
}

Comment.php

public function user () {
    return $this->belongsTo('App\User');
}

public function feed () {
    return $this->belongsTo('App\Feed');
}

Now I need to fetch all feeds (I have done with this), with comments count, likes count, and users details who have commented.

Ho can I get that in single query using Eloquent.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire