我被困在一个问题上:我创建了一个简单的用户跟随系统,以便用户可以相互关注。我使用名为follows
的表来存储关系。我在User
类中创建了一个hasMany
关系,并且在检索结果时我得到了我期望的结果,但是,我希望从用户表中获取一些其他信息,例如用户名,头像,等等。我该如何解决这个问题?Laravel 5.2用户/以下系统:hasMany Relation
的follows
表
// following_id is the person being followed
public function up()
{
Schema::create('follows', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('following_id')->unsigned();
$table->timestamps();
$table->unique(['user_id', 'following_id']);
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
的User
类
class User extends Authenticatable
{
// a user can have many followers
public function followers()
{
return $this->hasMany(Follow::class, 'following_id');
}
// a user may be following many people
public function following()
{
return $this->hasMany(Follow::class);
}
}
我打电话UsersController
的方法看到的结果
// route is /{username}/followers
public function followers($username)
{
$user = User::where('username', $username)->first();
// get the user's followers
$followers = $user->following;
return $followers;
}
目前的结果是
[
{
id: 24,
user_id: 3,
following_id: 1,
created_at: "2016-02-13 11:42:59",
updated_at: "2016-02-13 11:43:02"
}
]
但是,我希望它们如下:其中fredflintstone
是ID为1的用户;例如。;谁是下用户3
[
{
id: 24,
user_id: 3,
following_id: 1,
following_username: 'fredflintstone',
created_at: "2016-02-13 11:42:59",
updated_at: "2016-02-13 11:43:02"
}
]
用户我也创建了一个模型Follow
,这是目前空。我尝试在其中添加一个逆belongsTo
关系,但它不起作用。可能我做错了吗?
这样做User :: where('username',$ username) - > with('following') - > first(); –
@AmirBar无法让它工作。 – timgavin
为什么?你需要给更多的信息,当你做dd(User :: where('username',$ username) - > with('following') - > first())会发生什么? –