【问题标题】:laravel one to one relationshiplaravel 一对一关系
【发布时间】:2014-08-22 11:17:49
【问题描述】:

我有 xml_document 包含这些列的表:

id
general_information_id

我有 general_information 包含这些列的表:

id
domain
log_file

它们之间的关系是一对一的。

我是否正确地建立了关系?或者我需要将xml_document_id 列添加到general_information 表中。

其次:

我已经向xml_doucment 添加了一行,现在我想向general_information 添加一行并将这个新行链接到xml_document

我试过了:

 $xmlDocument = XmlDocument::find(Input::get(4));
            $generalInformation = new GeneralInformation($dataGeneralInformation);
            $generalInformation->xmlDocument()->associate($xmlDocument);
            //$xmlDocument->generalInformation()->attach($generalInformation);
            $generalInformation->save();
            $xmlDocument->save();

但我收到xml_document_id 列在general_information 表中不存在的错误。

我尝试用attach 替换associate,但我发现attach 不是现有函数。

请帮助我,我尝试过这种一对一的关系,我不知道做 id 的正确方法是什么。我不知道在数据库中的哪里添加列以及在模型中做什么。我已经尝试了很多东西,但仍然很困惑。

更新 1

class GeneralInformation extends  Eloquent{
.....   
public function xmlDocument(){
        return $this->belongsTo('XmlDocument');
    }
}


class XmlDocument extends Eloquent {
....
 public  function  generalInformation(){
        return $this->hasOne('GeneralInformation','general_information_id');
    }
}

【问题讨论】:

  • 请问为什么有人会否决这样的问题?至少留个便条。我一直试图理解这个问题 4 天。我向你展示了很好的努力。
  • 投反对票的不是我,但可能是因为格式不佳以及缺少代码中最重要的部分,即您的模型。
  • 您应该提供更多信息,两个表是如何关联的,哪一个是子表中的foreign key,这里的孩子是谁?
  • @WereWolf-TheAlpha 这是一对一的关系,所以问题的一部分是请告诉我是否应该在general_information 表中创建外键。我应该放两个外键吗?每张桌子一个?这是不可能的,对吧?

标签: php mysql database laravel laravel-4


【解决方案1】:

要建立one-to-one关系,需要将父表的primary key作为foreign key存储在子表中。因此,如果xml_document 是父级并且如果它包含许多general_information,那么xml_documentid 字段应该在general_information 表中以xml_document_id 的形式出现。

因此,您可以像这样构建one-to-one 关系:

// xml_document model
public function generalInfo()
{
    return $this->hasOne('GeneralInformation');
}

然后声明GeneralInformation 模型。

【讨论】:

  • 所以你是说我需要从xml_document 表中删除general_information_id 并将xml_document_id 添加到general_information 表中?对吗?
  • 我不明白parent 的意思,但如果在personpictures 的关系中,(一对多)父母是person,所以在这里父级是xmldocument。每个 xml 文档都有一个general_information(一个表)和一个details_information(另一个表)和一个master_information(另一个表)。找到我的朋友了吗?
  • 如果我理解正确的话,除了 hasOne 到 hasMany 之外,一对一和一对多的完全相同的代码。正确的?数据库和 laravel 模型中的确切代码
  • 那么您的general_information 表应该包含xml_document_idxml_document.id 应该是primary keyxml_document 表和xml_document_id 应该是foreign keygeneral_information 表中。跨度>
  • 是的,one-to-one 应该与 hasOne 相同。
【解决方案2】:

这就是你想要的:

class GeneralInformation extends  Eloquent
{
  public function xmlDocument()
  {
    return $this->hasOne('XmlDocument');
  }
}


class XmlDocument extends Eloquent
{

  public function generalInformation()
  {
    return $this->belongsTo('GeneralInformation','general_information_id');
  }
}

【讨论】:

  • 非常感谢,但我已经得到了答案。另外,您提供的代码正是我在问题中显示的代码。
  • 其实不是。 hasOnebelongsTo 已切换,因为您在问题中将它们倒退了。那是关键。子表(不带外键的表)的父表(带外键的表)始终为hasOne。孩子总是belongsTo父母。
猜你喜欢
  • 2018-09-27
  • 2018-10-03
  • 2018-05-29
  • 2013-10-21
  • 2014-06-24
  • 2018-04-20
  • 1970-01-01
相关资源
最近更新 更多