Support the ongoing development of Laravel.io →
Database Eloquent

Good morning to all guys!

I have two table. "user" and "user_user". In the table "user" i have save the users registered with the site. Thes users can these users have the possinlità to be followed each other giving rise to the cross table "user_user".

These are the fields:

user : id_user | username

user_user : id_user | id_userseguito

"id_userseguito" is the id of the user who is followed.

I should be able to make a function in eloquent that passing the user id associated with "id_user" table "user_user" give me back all the usernames of the users that this user is following.

The normal query would be: SELECT user.username FROM user, user_user WHERE user_user.id_user = $id_user AND user_user.id_userseguito = user.id_user

But eloquent as I can translate this query? Thanks for your help.

I have the class "User" and the class "UserUser"

Using belongToMany() function

Last updated 2 years ago.
0

You don't need a UserUser model.

class User extends Eloquent{

public function followers(){//they follow this user
return $this->belongsToMany('User', 'user_user', 'id_user', 'id_userseguito');
}

public function followings(){//this user follows them
return $this->belongsToMany('User', 'user_user', 'id_userseguito', 'id_user');
}
}

Check if it works.

$user = User::find($id);

$followerNames = array();
foreach($user->followers as $follower){
$followerNames[] = $follower->username;
}

$followingNames = array();
foreach($user->followings as $following){
$followingNames[] = $following->username;
}

return array(
'user' => $user,
'followers' => $followerNames,
'followings' => $followingNames 
);

De nada :P

Last updated 2 years ago.
0

Thanks!!!!! ;)

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

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.