我试图将用户表中的用户ID作为外键存储在另一个汽车表中。 用户表:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('userid')->unique();
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
汽车桌:
public function up()
{
Schema::create('cars', function (Blueprint $table) {
$table->string('plateno')->primary()->unique();
$table->string('brand');
$table->string('model');
$table->string('user_id')->nullable();
$table->foreign('user_id')->references('userid')->on('users')->onDelete('cascade')->onUpdate('cascade');
$table->timestamps();
});
}
用户模型和汽车模型之间存在1到1的关系。
class User extends Authenticatable
{ 使用可通知的;
protected $fillable = [
'userid', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function cars()
{
return $this->hasOne('App\Car', 'plateno' );
}
}
这是CarController的存储功能
public function store(Request $request)
{
$this->validate($request, [
'plateno' => 'required',
'brand' => 'required',
'model' => 'required'
]);
$cars= new \App\Car;
$cars->plateno=$request->get('plateno');
$cars->brand=$request->get('brand');
$cars->model=$request->get('model');
$cars=Auth::user()->userid;
$cars->save();
return redirect('car')->with('success', 'User car has been added.');
}
谢谢。
答案 0 :(得分:0)
您在这里遇到错误:
$cars= new \App\Car;
$cars->plateno=$request->get('plateno');
$cars->brand=$request->get('brand');
$cars->model=$request->get('model');
$cars=Auth::user()->userid; // Here must be $cars->user_id = Auth::user()->userid;
$cars->save();
用$cars=Auth::user()->userid;
替换$cars->user_id = Auth::user()->userId;
;