Laravel 4 Relations belongsTo on multiple tables

2.2k Views Asked by At

I'm trying to do a stystem of comments and posts with laravel 4 where 2 type of "user" can comments. For 2 type of "user" means that i have a table User and a table Teams and my expectations are that both can let comment on the posts of the opposite. Let'go with the logic that i used untill now:

Schema tables:

User Table

Table | Users

id       - integer autoincrement
fullname - string 20

Team table

Table | Teams

id        - integer autoincrement 
fullname  - string 50

Posts table

Table | Posts

id         - integer autoincrement
text       - text
id_poster  - integer
type_id    - integer // if is 1 the id_poster filed belongs to user else if 2 belongs to team

Comments Table

Table | Comments

id          - integer autoincrement
id_post     - integer
id_poster   - integer
id_type     - integer
text        - text

And now let's go with the relations:

Users relation

   Class User extends Eloquent {

     protected $table = "users";

     function posts() {
       return $this->hasMany('Post','id_poster');
     }

    function comments() {
     return $this->hasMany('Comment','id_poster');
    }
  }

Team relation

Class Team extends Eloquent {
  protected = $table = "teams";

  function posts() {
    return $this->hasMany('Post','id_poster');
  }

  function comments() {
    return $this->hasMany('Comment','id_poster');
  }

}

Posts relation

Class Post extends Eloquent {

 protected $table = "posts";

 function users() {
   $this->belongsTo('User','id_poster');
 }

 function teams() {
   return $this->belongsTo('Team','id_poster');
 }

 function comments() {
   return $this->hasMany('Comment','id_post');
 }

}

Comments relation

Class Comment extends Eloquent {

 protected $table = "comments";

 function posts() {
   return $this->belongsTo('Post','id_post');
 }

 function teams() {
   return $this->belongsTo('Team','id_poster');
 }

}

with this kind of relations i can get posts and comments about just an individual category:

example i do the results for the users posts and comments

$posts = new Post;
$get_post = $posts->with('users','comments.users')->where('type_id','=',1)->get();

i can display

  • users posts and users comments OR
  • teams posts and teams comments

but not

  • Users posts and teams / users comments
  • Team posts and users / teams comment

The datas need it for my output about the comments are: - id_poster - fullname - id_type - text

In few words my question is:

What i have to change and why for do appear the comments of both the "user"?

0

There are 0 best solutions below