laravel 在laravel中使用外键保存对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37680614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Save object with foreign keys in laravel
提问by dimitrisd
I use PHP, Laravel 5.2 and MySQL.
我使用 PHP、Laravel 5.2 和 MySQL。
During user registration, I need to create a new Patient. But, Patient has user id, contact id and guardian id(foreign keys).
在用户注册期间,我需要创建一个新的 Patient。但是,患者有用户 ID、联系人 ID 和监护人 ID(外键)。
When I try to save() the patient, I get the following exception:
当我尝试 save() 患者时,出现以下异常:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'patient_id' in 'field list' (SQL: update
users
setpatient_id
= 0,updated_at
= 2016-06-07 12:59:35 whereid
= 6)
SQLSTATE[42S22]:未找到列:1054 'field list' 中的未知列 'patient_id'(SQL:更新
users
集patient_id
= 0,updated_at
= 2016-06-07 12:59:35 whereid
= 6)
The problem is that I DO NOT have patient_idcolumn. Instead I have patientId.
问题是我没有Patient_id列。相反,我有PatientId。
I don't know how to fix this issue. Any help will be appreciated. I can include the migration files if this is important.
我不知道如何解决这个问题。任何帮助将不胜感激。如果这很重要,我可以包含迁移文件。
UserController.php
用户控制器.php
public function postSignUp(Request $request)
{
$this->validate($request,[
'email' => 'required|email|unique:users',
'name' => 'required|max:100',
'password' => 'required|min:6'
]);
$guardian = new Guardian();
$guardian->guardianId = Uuid::generate();;
$guardian->save();
$contact = new Contact();
$contact->contactId = Uuid::generate();
$contact->save();
$user = new User();
$user->email = $request['email'];
$user->name = $request['name'];
$user->password = bcrypt($request['password']);
$user->save();
$patient = new Patient();
$patient->patientId = (string)Uuid::generate();
$patient->user()->save($user);
$patient->contact()->save($contact);
$patient->guardian()->save(guardian);
$patient->save();
Auth::login($user);
// return redirect()->route('dashboard');
}
Patient.php
病人.php
class Patient extends Model
{
protected $primaryKey='patientId';
public $incrementing = 'false';
public $timestamps = true;
public function user()
{
return $this->hasOne('App\User');
}
public function contact()
{
return $this->hasOne('App\Contact');
}
public function guardian()
{
return $this->hasOne('App\Guardian');
}
public function allergies()
{
return $this->belongsToMany('App\PatientToAllergyAlert');
}
public function medicalAlerts()
{
return $this->belongsToMany('App\PatientToMedicalAlert');
}
}
User.php
用户名.php
class User extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function patient()
{
return $this->belongsTo('App\Patient');
}
}
Contact.php
联系方式.php
class Contact extends Model
{
protected $table = 'contacts';
protected $primaryKey = 'contactId';
public $timestamps = true;
public $incrementing = 'false';
public function contact()
{
return $this->belongsTo('App\Patient');
}
}
Guardian.php
守护者.php
class Guardian extends Model
{
protected $table = 'guardians';
protected $primaryKey = 'guardianId';
public $timestamps = true;
public $incrementing = 'false';
public function contact()
{
return $this->belongsTo('App\Patient');
}
}
回答by Tadas Paplauskas
You have not defined relationships correctly. First of all, fill in table fields into $fillable array in Patient, Contact, Guardian classes (just like in User class).
您没有正确定义关系。首先,在 Patient、Contact、Guardian 类(就像在 User 类中)将表字段填充到 $fillable 数组中。
If you want to use hasOne relationship between Patient and User, you're gonna need user_id field on patients table. You can alternatively use belongsTo relationship.
如果您想在 Patient 和 User 之间使用 hasOne 关系,则需要患者表上的 user_id 字段。您也可以使用belongsTo 关系。
If you want to use custom column names, just specify them in relationship methods:
如果要使用自定义列名,只需在关系方法中指定它们:
public function user()
{
return $this->hasOne('App\User', 'id', 'user_id');
// alternatively
return $this->belongsTo('App\User', 'user_id', 'id');
}
Just go through documentation without skipping paragraphs and you will get going in a few minutes :) https://laravel.com/docs/5.1/eloquent-relationships#defining-relationships
只需阅读文档而不跳过段落,您将在几分钟内开始:) https://laravel.com/docs/5.1/eloquent-relationships#defining-relationships
Also, this will not work:
此外,这将不起作用:
$patient = new Patient();
$patient->patientId = (string)Uuid::generate();
$patient->user()->save($user);
new Patient() only creates the object, but does not store it in DB, so you will not be able to save relationships. You need to create the object and store it to DB to avoid this problem:
new Patient() 只创建对象,但不会将其存储在数据库中,因此您将无法保存关系。您需要创建对象并将其存储到 DB 以避免此问题:
$patient = Patient::create(['patientId' => (string)Uuid::generate()]);
$patient->user()->save($user);
...
// or
$patient = new Patient();
$patient->patientId = (string)Uuid::generate();
$patient->save();
$patient->user()->save($user);
...