2016-02-13 83 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'); 
}