与Laravel的数据库关系 [英] Database Relationship with Laravel
问题描述
我无法根据我的数据库结构将数据插入到我的数据库中.我有3张桌子. Company table
Users table
branches table
.
i am having trouble inserting data into my database according to my database structure. I have 3 tables. Company table
Users table
branches table
.
现在这就是我在这些表之间建立关系的方式.
Now this is how i made the relationship between these tables.
公司表和用户表具有一对多关系
公司表和分支机构表具有一对多关系
分支表和用户表具有一对多的关系ip
这是我的模型的样子
PS :我只是数据库和laravel的初学者
PS: I am only a beginner with database and 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');
}
现在,当用户注册时,只有公司表填充了它的详细信息,但用户表和分支表却没有填充,我得到了错误
Now, when a user registers, only the company table is filled with it details but the user table and branch table is not filled and i get the error
"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中的方式
This is how i save the data in the 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
]);
}
推荐答案
您应该尝试一下,这可能会对您有所帮助:
You should try this may be its help for you:
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");
}
}
这篇关于与Laravel的数据库关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!