Php Laravel 5.2关系有许多与另一个唯一标识符的关系

Php Laravel 5.2关系有许多与另一个唯一标识符的关系,php,mysql,laravel,Php,Mysql,Laravel,因此,我正在学习laravel,并试图建立一个阻止用户列表,例如,如果你想阻止用户查看你的个人资料,你会阻止他们,我已经这样做了,但我只是想知道我这样做的方式是否正确 下面是我所做的。我的主要问题是,是否有另一种方法来设置标识符,而不必创建一个名为unique_id的新db字段,在该字段中,我会将两个用户id都放进去,然后每次查询它 数据库迁移: Schema::create('blocked_users', function(Blueprint $table) { $tab

因此,我正在学习laravel,并试图建立一个阻止用户列表,例如,如果你想阻止用户查看你的个人资料,你会阻止他们,我已经这样做了,但我只是想知道我这样做的方式是否正确

下面是我所做的。我的主要问题是,是否有另一种方法来设置标识符,而不必创建一个名为unique_id的新db字段,在该字段中,我会将两个用户id都放进去,然后每次查询它

数据库迁移:

  Schema::create('blocked_users', function(Blueprint $table)
  {
      $table->increments('id');
      $table->integer('user_id')->unsigned();
      $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
      $table->integer('blocked_user_id')->unsigned();
      $table->foreign('blocked_user_id')->references('id')->on('users')->onDelete('cascade');
      $table->integer('unique_id')->unique();
      $table->text('reason')->nullable();
      $table->timestamps();
  });
用户模型

public function BlockedUsers()
{
    return $this->hasMany('App\Models\User\BlockedUsers');
}
然后,当我阻止一个用户时,我输入被阻止的用户id和当前用户id作为唯一的\u id

然后这是我正在做的混乱的部分,我相信应该有一个更简单的方法

if (BlockedUsers::whereUniqueId($user->id.Auth::user()->id)->exists()) {
    $blocked = 1;
 } else {
    $blocked = 0;
 }
我正在想办法在用户模型中设置一个函数,以检查用户id是否等于当前用户,以及被阻止的用户id是否等于用户配置文件id

我能想到的就是

public function isUserBlocked()
{
    return $this->hasOne('App\Models\User\BlockedUsers', 'blocked_user_id');
}

但显然这是行不通的。

我认为您可以在应用于路由的一些中间件中处理这个问题

php artisan make:middleware UserCanViewProfile
然后,我们假设中间件将应用于具有
概要文件
模型的路由,例如:

Route::get('/profile/{profile}', 'ProfileController@show');
现在,我们将通过
路由访问中间件中的配置文件实例,然后检查用户是否有包含
配置文件用户id
身份验证用户id
的块

$profile = $this->route('profile');
$$block = BlockedUsers::where('user_id', $profile->user->id)->where('blocked_user_id', auth()->user()->id)->first();

if (empty($block)) {
    return $next($request);    
} else {
    abort(403, 'You are not allowed to view that profile!');
}
当然,您需要在
$routeMiddleware
下的
App\Http\Kernel
文件中注册此中间件,如下所示:

'usercanviewprofile' => \App\Http\Middleware\UserCanViewProfile::class,
然后将其应用于您的
路线

Route::group(['middleware' => ['usercanviewprofile'], 'prefix' => 'profile'], function(){
    Route::get('{profile}', 'ProfileController@show');
});
或者如果您使用的是
CRUD
模式:

Route::resource('profile', 'ProfileController')->middleware('usercanviewprofile');

希望这能有所帮助。

我真的很抱歉,我已经设置了检查用户是否被阻止的方法,我只是想知道我的方法是否正确。我已经这样做了,但是我只是想知道我这样做的方式是否正确。“下面是我所做的。我的主要问题是,是否有其他方法可以设置标识符,而不必创建一个名为unique_id的新db字段,在该字段中,我会将两个用户id都放进去,然后每次查询”@Unifx是的,我上面概述的方法不需要这些。哦,对不起,我没有看到这一部分,再次感谢