Support the ongoing development of Laravel.io →
Database Eloquent

Hello guys, I got this big question on this scenario:

I'm building a easy post and comment system, but with the difference that i have 2 main entity, wich are:

  • User
  • Team

So i have abviously 2 tables for it:

Table User:

id | name | surname | fullname     |    image_profile |
1    jhon     smith       jhon smith       apple.jpg

Table Team

id | fullname     | image_profile |
1    BKA Sport   three.jpg

Each user can let posts or comments and same thing for the team.

So i have setup my table Post with a column that difference the entity of the poster like so

Table Post

id | title_post |    body    | poster_id | poster_type | wall_id | wall_type
1     test          woo         1              User              1            Team
2     test 2       excellent    1              Team             1            User
3     test3        perfect       1              Team             1            Team

as you can see i setup even the column wall where this post as been released, in this case the User with ID 1 as wrote a post on the Wall of the team with ID 1, and the Team has wrote on the Wall of the User with ID 1. on the third result the Team has leaved a post on his own wall.

Now if i want to select all the wall posts of the "entity or poster_type" Team associating it the right entity how i have to set up my relations?

For now i just did a dirty solution without relationship but merging the results with an array, i think it's heavy for the server but i didn't find any way using relations. I even thought to use the polymorphic relation but it seem does't do the job well.

Here how i did for now

<?php

$posts = Post::where('wall_id','=','1')->where('wall_type','=','Team')->get()->toArray(); 

// I get just the id of the current posters
foreach ($posts as $key => $value) {
            if ($value["poster_type"] == "User") {
                $poster['User'][$key]['id'] = $value['poster_id'];
            }

            if ($value['poster_type'] == "Team") {
                $poster['Team'][$key]['id'] = $value['poster_id'];
            }
 }

// all ids of the users
$user_ids = array_fetch($poster['User'],'id');
// all ids of the teams
$team_ids = array_fetch($poster['Team'],'id');

$users_informations = User::whereIn('id',array_unique($user_ids))->get()->toarray();
$teams_informations = User::whereIn('id',array_unique($team_ids))->get()->toarray();

// Here i merge the results 

Any ideas?

Last updated 3 years ago.
0

I did but it'is not work how expected, thank you anyway for the answer.

Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

fenos fenos Joined 8 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.