基于每个用户应用唯一验证检查



我在Laravel中为个人理财应用程序创建登录/注册系统,遇到了数据库中数据冲突的问题。例如,如果名称为UserA的注册用户使用名称为汽车创建费用,则名称为用户B的注册用户无法创建名称为汽车的费用,因为该名称列使用唯一关键字进行验证,并且Car已经存在于数据库中,但是由其他用户创建,这不是我所期望的。你能看看我的代码,如果可能的话,告诉我我在哪里犯了错误。控制器代码:

public function store(Request $request)
{
$user_id=auth()->user()->id;
$user=User::find($user_id);
$this->validate($request, [
'Name'=>'required|unique:personal_accountings,Name,'.$user_id,
'SumOfMoney'=>'numeric'],
['Name.required'=>'Name is empty' ,
'Name.unique'=>'Name already exists']
);
$personal= new PersonalAccounting();
$personal->Name=$request->input('Name');
$personal->SumOfMoney=$request->input('SumOfMoney');
$personal->user_id= auth()->user()->id;
$personal->save(); 

个人计数型号代码:

class PersonalAccounting extends Model
{
public function user(){
return $this->belongsTo('AppUser');
}
}

用户型号代码:

public function personalAccounting(){
return $this->hasMany('AppPersonalAccounting');
}
Schema::create('personal_accountings', function (Blueprint $table) {
$table->increments('id');
$table->string('TypeOfAccounting');
$table->string('Name');
$table->integer('SumOfMoney')->unsigned();
$table->mediumText("Comments")->nullable();
$table->timestamps();
});

下一次迁移

Schema::table('personal_accountings', function($table){
$table->integer('user_id');
});

在标题"添加附加 Where 子句"的文档中对此进行了解释。

根据文档中的示例使用如下规则:

'Name' => ['required', Rule::unique('personal_accountings')->where(function ($query) {
return $query->where('user_id', $user_id);
})]

也应该可以使用简写形式:

'Name' => ['required', Rule::unique('personal_accountings')->where('user_id', $user_id)]

要使 Rule 类可用,您需要引用命名空间

use IlluminateValidationRule;

这不是代码问题,而是您用于数据库的模型问题。表的唯一键应由user_id和名称组成,而不仅仅是由名称列组成。

最新更新