我在根据数据库结构将数据插入数据库时遇到问题。我有3张桌子。 Company table
Users table
branches table
。
现在这就是我如何建立这些表之间的关系。
公司表和用户表具有一对多的关系
公司表和分支表具有一对多的关系
分支表和用户表有一对多关系
这就是我的模型的样子
PS :我只是数据库和laravel的初学者
公司模式
public function branches()
{
return $this->hasMany('App\Branch');
}
public function users()
{
return $this->hasMany('App\User');
}
用户模型
public function company()
{
return $this->belongsTo('App\Company')
->withTimestamps();
}
public function branches()
{
return $this->belongsTo('App\Branch')
->withTimestamps();
}
分支模型
public function company()
{
return $this->belongsTo('App\Company');
}
public function users()
{
return $this->hasMany('App\User');
}
现在,当用户注册时,只有公司表中填充了详细信息,但用户表和分支表未填充,我收到错误
"SQLSTATE[HY000]: General error: 1364 Field 'company_id' doesn't have a default value (SQL: insert into `branches` (`name`, `updated_at`, `created_at`) values (Virginia, 2017-10-14 03:19:38, 2017-10-14 03:19:38)) ◀"
这就是我在RegisterController中保存数据的方法
RegisterController
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'phone' => $data['phone'],
'password' => bcrypt($data['password']),
"company_id" => Company::create(
[
"name" => $data['rname'],
"email" => $data['remail'],
"phone" => $data['rphone'],
"address" => $data['raddress']
]
)->id,
"branch_id" => Branch::create (
[
"name" => $data['rbranch']
]
)->id
]);
}
答案 0 :(得分:0)
您需要创建可以为空的外键...
在迁移中,使用 - > nullable()函数...
$table->integer('company_id')->unsigned()->nullable();
这将让你最初不包括company_id,值将为null ...如果没有nullable(),数据库将不允许空值......
希望这有帮助。
答案 1 :(得分:0)
您应该尝试这可能对您有所帮助:
protected function create(array $data)
{
$company = Company::create(
[
"name" => $data['rname'],
"email" => $data['remail'],
"phone" => $data['rphone'],
"address" => $data['raddress']
]);
更新了答案
$branch = Branch::create (
[
"name" => $data['rbranch'],
"company_id" => $company->id
]
);
if(isset($company->id) && isset($branch->id)){
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'phone' => $data['phone'],
'password' => bcrypt($data['password']),
"company_id" => $company->id,
"branch_id" => $branch->id
]);
} else{
return redirect()->back()->withFlashDanger("company or branch no successfully insterted");
}
}