本文介绍了如何建立有关系的口才模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何创建具有关系的雄辩模型?
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('App\Employee');
}
}
之后,您可以在控制器中执行以下操作:
After that in your controller you can do:
$person = Person::create($personData);
$person->employee()->create($employeeData);
如 @Alexey Mezenin 所述,您可以使用:
$person = Person::create(request()->all());
$person->employee()->create(request()->all());
也将是相反的:
class Employee extends Model
{
protected $fillable = ['position'];
public function person()
{
return $this->belongsTo('App\Person');
}
}
这篇关于如何建立有关系的口才模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!