如何创建具有关系的 Eloquent 模型? [英] How to create Eloquent model with relationship?
本文介绍了如何创建具有关系的 Eloquent 模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何创建带有关系的 Eloquent 模型?
How to create Eloquent model with relationship?
我有:
人员表
id
firstname
lastname
员工表
id
person_id
position
我想做这样的事情:
Employee::create([
'firstname' => 'Jack',
'lastname' => 'London',
'position' => 'writer'
])
我知道,那可以创建两个模型然后将它们关联起来.但是有没有办法让它更漂亮?
I know, that can create two model and then associate their. But may be there is a way do this more beautiful?
推荐答案
首先,你必须在你的 Person 模型中创建关系
First, you have to create relation in your Person model
class Person extends Model
{
protected $fillable = ['firstname', 'lastname'];
public function employee()
{
return $this->hasOne('AppEmployee');
}
}
之后在您的控制器中您可以执行以下操作:
After that in your controller you can do:
$person = Person::create($personData);
$person->employee()->create($employeeData);
正如 @Alexey Mezenin 提到的,您可以使用:
As @Alexey Mezenin mentioned you can use:
$person = Person::create(request()->all());
$person->employee()->create(request()->all());
反之亦然:
class Employee extends Model
{
protected $fillable = ['position'];
public function person()
{
return $this->belongsTo('AppPerson');
}
}
这篇关于如何创建具有关系的 Eloquent 模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文