laravel 如何创建具有关系的 Eloquent 模型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41509900/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:04:57  来源:igfitidea点击:

How to create Eloquent model with relationship?

laravellaravel-5eloquentlaravel-5.2

提问by Stanislav

How to create Eloquent model with relationship?

如何创建具有关系的 Eloquent 模型?

I have:

我有:

Person table

人表

id
firstname
lastname

Employee table

员工表

id
person_id
position

I want to do something like this:

我想做这样的事情:

Employee::create([
'firstname' => 'Hyman',
'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?

我知道,那可以创建两个模型然后将它们关联起来。但可能有办法做到这一点更漂亮吗?

回答by DokiCRO

First, you have to create relation in your Person model

首先,您必须在 Person 模型中创建关系

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);

As @Alexey Mezeninmentioned you can use:

正如@Alexey Mezenin提到的,您可以使用:

$person = Person::create(request()->all());
$person->employee()->create(request()->all());

Also inverse would be:

反之亦然:

class Employee extends Model
{
    protected $fillable = ['position'];

    public function person()
    {
        return $this->belongsTo('App\Person');
    }
}

回答by Alexey Mezenin

You still need to create person first, so if you're looking for readable and consize solution, you can do is this:

您仍然需要先创建 person,所以如果您正在寻找可读和精简的解决方案,您可以这样做:

$data = [
    'firstname' => 'Hyman',
    'lastname' => 'London',
    'position' => 'writer'
];

$person = Person::create($data);
$person->employee()->create($data);