How to create Eloquent model with relationship?

情到浓时终转凉″ 提交于 2019-12-06 00:52:47

问题


How to create Eloquent model with relationship?

I have:

Person table

id
firstname
lastname

Employee table

id
person_id
position

I want to do something like this:

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?


回答1:


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

As @Alexey Mezenin mentioned you can use:

$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');
    }
}



回答2:


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

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

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


来源:https://stackoverflow.com/questions/41509900/how-to-create-eloquent-model-with-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!