【问题标题】:Laravel one-to-one relationship not associatingLaravel一对一关系不关联
【发布时间】:2014-06-24 09:42:19
【问题描述】:

我有两个模型,模板和状态,它们通过一对一的关系关联。国家属于模板,

使用以下迁移创建外键:

public function up()
{
    Schema::table(
        'templates',
        function (Blueprint $table) {
            $table->dropColumn('state');

            $table->integer('state_id')->unsigned()->index()->nullable();
            $table->foreign('state_id')->references('id')->on('template_states');
        }
    );
}

然后,Template 模型类将 state 字段定义为 hasOne 关系:

public function state()
{
    return $this->hasOne('TemplateState', 'id', 'state_id');
}

并且 TemplateState 模型类定义了反向所属位:

public function template()
{
    return $this->belongsTo('Template');
}

一旦在数据库中创建,我很难将状态与其模板关联起来。看看下面的 Tinker:

[1] > $t = Template::find(1);
// object(Template)(
//   'incrementing' => true,
//   'timestamps' => true,
//   'exists' => true
// )
[2] > $t->alias;
// 'travel_journal'
[3] > $s = TemplateState::find(1);
// object(TemplateState)(
//   'incrementing' => true,
//   'timestamps' => true,
//   'exists' => true
// )
[4] > $s->state;
// 'pending'
[5] > $t->state()->save($s);
// object(TemplateState)(
//   'incrementing' => true,
//   'timestamps' => true,
//   'exists' => true
// )
[6] > $t->state->state;

在修补程序的第 [6] 步,调用 $t->state->state,我可以看到这两个模型没有关联,并且查看数据库,模板的 state_id 仍然为空。

我不知道我做错了什么,谁能帮忙!

【问题讨论】:

    标签: laravel laravel-4 eloquent


    【解决方案1】:

    我已经设法通过更改以下内容使其正常工作:

    状态模型:

    public function template()
    {
        return $this->belongsTo('Template');
    }
    

    模板模型:

    public function state()
    {
        return $this->hasOne('TemplateState');
    }
    

    并将外键添加到 TemplateState 模型中。

    现在,调用类似:

    $template->state()->save($state);
    

    工作正常。

    【讨论】:

    • 确保它真的如你所愿
    • 谢谢@deczo。我 100% 确定它有效。系统能够正确地将模板与其相关状态相关联。在修补程序中玩耍,现在看来一切都按预期工作。
    【解决方案2】:

    你的关系不对,这是你需要的:

    // Template model
    public function state()
    {
        return $this->belongsTo('TemplateState', 'state_id');
    }
    
    // TemplateState model
    public function template()
    {
        return $this->hasOne('Template', 'state_id');
    }
    

    【讨论】:

    • 我理解你的意思是我应该让 Template 属于 TemplateState,所以颠倒我目前拥有的?
    • 是的,hasOne/hasMany 需要另一张表上的外键,这与belongsTo 相反。
    猜你喜欢
    • 2018-09-27
    • 2014-08-22
    • 2018-10-03
    • 2018-05-29
    • 2013-10-21
    • 2018-04-20
    • 1970-01-01
    相关资源
    最近更新 更多