我遇到了一个问题:我创建了一个简单的用户跟踪系统,因此用户可以互相关注。我正在使用名为follows
的表来存储关系。我在我的hasMany
类中创建了一个User
关系,并且在检索结果时我得到了我期望的结果,但是,我想从users表中获取一些额外的信息,例如用户名,头像等。我该怎么做?
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 :(得分:0)
我一直在使用laravel很长一段时间,如果laravel内置了'with'的模型,我建议你使用join
以下是使用连接的代码,根据您的使用进行修改
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;
}
答案 1 :(得分:0)
想出来。我需要将users表加入查询。
public function following()
{
return $this->hasMany(Follow::class, 'user_id')
->join('users', 'users.id', '=', 'follows.following_id')
->select('user_id','username');
}