问题描述:

i have two tables: Users and Followers.

user

id, username

1, foo

2, bar

3, test

followers

id, user_id_follows, user_id_followed

1, 2, 1

2, 3, 1

Which means that the users "bar" and "test" follow the user "foo".

I would like to have a result-set like:

[

id: "foo",

username: "bar",

followers: ["bar", "test"]

]

Alternatively as JSON object.

Is this possible with eloquent ORM? user has a hasMany-relationship to follower and follower belongsTo user.

Is it possible to get the relations but only the usernames of the followers?

I also tried to do this via raw-sql query. But using DB::select(DB::raw($query)); gets me an non-multidimensional object which means that "followers" only has "bar" and not both followers.

So what is the best way to get a multidimensional result-set?

Can i still rely on eloquentORM? How?

Thank you and best regards

Phil

网友答案:

Found a much better way. What we will do is create a many to many relationship with the users table to the users table and use your followers table as the pivot table. I've also done some extra work so you can view both followeds and followers for a user.

Unfortunately, the way you have your tables setup didn't make a lot of sense to me, so my followers table looks like id, user_id, follow_id. This way, I can easily find who a user is following by looking up that user's id in the user_id column and I can see who that user is followed by, by looking up his user_id in the follow_id column. Maybe this is what you meant with your table, in which case, you could just drop in the column names you have. With that in mind, here is what I did.

In your User model.

public function followers()
{
    return $this->belongsToMany('User','followers','user_id_followed','user_id_follows');
}

public function followeds()
{
    return $this->belongsToMany('User','followers','user_id_follows','user_id_followed');
}

In my controller, to get the json....

$user = User::find(1);
$user->load('followers');
$user->load('followeds');
$json = $user->toJson();
echo $json;

Obviously if you just wanted the followers, just $user->load('followers');

相关阅读:
Top