gpt4 book ai didi

php - Laravel 5.2 关系 hasMany 与另一个唯一标识符

转载 作者:行者123 更新时间:2023-11-28 23:29:12 25 4
gpt4 key购买 nike

所以我正在学习 laravel 并尝试设置一个被阻止的用户列表,例如,如果你想阻止一个用户查看你的个人资料,你会阻止他们,我已经这样做了但是我只是想知道我是否有完成它是正确的。

下面是我做的。我的主要问题是,是否有另一种方法可以设置标识符,而无需创建一个名为 unique_id 的新数据库字段,我可以在其中放入两个用户 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 作为 unique_id

然后这是我正在做的困惑部分,我相信应该有更简单的方法。

if (BlockedUsers::whereUniqueId($user->id.Auth::user()->id)->exists()) {
$blocked = 1;
} else {
$blocked = 0;
}

我正在想办法在用户模型中设置一个函数来检查 user_id 是否等于当前用户以及 blocked_user_id 是否等于用户个人资料 ID。

我能想到的就是

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

但显然这是行不通的。

最佳答案

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

php artisan make:middleware UserCanViewProfile

然后我们假设中间件将应用于具有 Profile 模型的路由,例如:

Route::get('/profile/{profile}', 'ProfileController@show');

现在我们将通过 route 访问我们的中间件中的配置文件实例,然后我们将检查用户是否有包含 profile 用户 id 的 block auth 用户 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');

希望这对您有所帮助。

关于php - Laravel 5.2 关系 hasMany 与另一个唯一标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37957789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com