我被困在一個問題上:我創建了一個簡單的用戶跟隨系統,以便用戶可以相互關注。我使用名爲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())會發生什麼? –