2016-02-13 45 views
1

我被困在一個問題上:我創建了一個簡單的用戶跟隨系統,以便用戶可以相互關注。我使用名爲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關係,但它不起作用。可能我做錯了嗎?

+0

這樣做User :: where('username',$ username) - > with('following') - > first(); –

+0

@AmirBar無法讓它工作。 – timgavin

+0

爲什麼?你需要給更多的信息,當你做dd(User :: where('username',$ username) - > with('following') - > first())會發生什麼? –

回答

0

我一直在使用laravel很長一段時間,我建議你使用加入,而是如果laravel建模型「與」

下面是使用連接的代碼,根據您的使用修改

public function followers($username) 
     { 
      $user = User::where('username', $username)->first(); 
//Follower your model name for the follows table 
//if you dont have a model use DB::table('follows') instead 
      $followers=Follower::where('user_id',$user->id) 
       ->join('users as follower','follower.id','=','follows.following_id') 
       ->select('follows.id','follows.following_id','follows. user_id','follower.name as following_username')->get(); 


      return $followers; 
     } 
+0

這個解決方案確實能夠控制返回的內容......使用關係不可能嗎? – timgavin

+0

你可以使用這樣的東西 User :: where('username',$ username) - > with('following') - > first(); –

0

想通了。我需要將用戶表加入到查詢中。

public function following() 
{ 
    return $this->hasMany(Follow::class, 'user_id') 
     ->join('users', 'users.id', '=', 'follows.following_id') 
     ->select('user_id','username'); 
}