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

Laravel单向hasOne将相关对象保存为JSON,laravel,eloquent,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();

假设我有以下课程:

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);
以下是输出:(我刚刚从列中删除了反勾号)
illumb\Database\QueryException:SQLSTATE[42S22]:未找到列:1054“字段列表”中的未知列“mayor”(SQL:插入城镇(姓名、地区、市长、更新地址、创建地址)值(一些城镇,124,{“名字”:“Ricardo”,“姓氏”:“Miguelito”,“出生日期”:“1950-07-14 17:51:02”,“性别”:“男性”},2014-12-13 17:51:022014-12-13 17:51:02))

tldr; 1。您需要先保存父模型,然后保存子模型

2。推送不创建关系,只保存已存在(和已加载)的相关模型


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

$town->mayor = $mayor;
它所做的只是将
$mayor
模型保存为
$town
s属性。在这种情况下,它从未被视为一种关系

因此,以下是您需要的:

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

请注意:您在这里测试的都是雄辩的,您不需要。

您能给我们看一下
Person
型号吗?谢谢!是的,这里是拉威尔·努布:D
$town->mayor()->save($mayor)
确实可以正常工作,但我实际上是在测试模型的push()方法,看看它是否能发挥一些神奇的作用,但是很好。