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
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
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community