Laravel单向hasOne将相关对象保存为JSON

时间:2014-09-07 10:01:01

标签: laravel eloquent

假设我有以下课程:

class Town extends Eloquent {

    public function mayor()
    {
        return $this->hasOne('Person');
    }
} 

$town->push()如何被欺骗认为它有市长列?

$town = new Town();
$town->name = "Some Town";
$town->area = 124;

$mayor = new Person();
$mayor->first_name = "Ricardo";
$mayor->last_name = "Miguelito";
$mayor->birthdate = Carbon::createFromDate(1950, 7, 14);
$mayor->gender = Person::MALE;

$town->mayor = $mayor;
$town->push();

$this->assertGreaterThan(0, $town->mayor->id);

这是输出:(我刚从列中删除了反引号)     Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'mayor' in 'field list' (SQL: insert into towns (name, area, mayor, updated_at, created_at) values (Some Town, 124, {"first_name":"Ricardo","last_name":"Miguelito","birthdate":"1950-07-14 17:51:02","gender":"male"}, 2014-12-13 17:51:02, 2014-12-13 17:51:02))

1 个答案:

答案 0 :(得分:1)

tldr;

<强> 1。您需要先保存父模型,然后再保存子模型

<强> 2。 push不会创建关系,只保存已存在(和已加载)的相关模型


此外,雄辩的关系不会这样:

$town->mayor = $mayor;

它只是将$mayor模型保存为$town属性。在这种情况下,它从未被视为关系。

所以这就是你需要的:

$town = new Town();
// do what you need with town
$town->save();

$mayor = new Person();
// do what you need with mayor

$town->mayor()->save($mayor); 
// this associates mayor with town and saves it, it's equal to:

// if town relation is defined on mayor model:
$mayor->town()->associate($town); 
// otherwise:
$mayor->town_id = $town->id;

// then
$mayor->save();

请注意:你在这里测试的是Eloquent,你不需要它。