Laravel多对多关系返回null

时间:2018-11-17 16:32:22

标签: php laravel

我有一个与自己有很多关系的User类

public function following(){//Many To Many relationship
    return $this->belongsToMany(User::class, 'users_users', 'username', 'follower');
}
public function followers(){//Many To Many relationship
    return $this->belongsToMany(User::class, 'users_users', 'follower', 'username');
}

我使表迁移了users_users:

public function up()
{
    Schema::create('users_users', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();

        $table->string('username');
        $table->foreign('username')->references('username')->on('users');

        $table->string('follower');
        $table->foreign('follower')->references('username')->on('users');
    });
}

当我尝试获取一个用户的关注者时,当表中充满关系时,它将返回一个空数组。

public function getFollowers(String $username){
    $user = User::where('username',$username)->get();
    if(!$user){//si no ha encontrado el user con ese id
        return response()->json(['message' => 'User not found'],404);
    }
    return response()->json(['followers' => $user[0]->followers],200);
}

有什么主意吗? :/

0 个答案:

没有答案