简体   繁体   English

Laravel 4一对一关系

[英]Laravel 4 One to One relationship

I would like to have a one to one relationship with a pivot table or by referencing an ID in a table. 我想与数据透视表或通过引用表中的ID建立一对一的关系。

I currently have a Films table that has a one to many relationship with a Stock table, each stock item needs a format, however I would like the formats to be a set list of formats so I created a Formats table that only has 2 columns ID and Name 我目前有一个Films表,它与Stock表具有一对多的关系,每个stock项目都需要一种格式,但是我希望这些格式是一组格式列表,所以我创建了一个只有2列ID的Formats表和名称

Normally I would just add a Format_ID column to the Stock table however I'm unsure how this would work with the Eloquent ORM or if it's even possible / best practice 通常,我只是将一个Format_ID列添加到Stock表中,但是我不确定这如何与Eloquent ORM一起使用,或者不确定是否可行/最佳实践

Sorry if this is hard to understand, cant quite figure out the best way of explaining it 抱歉,如果这很难理解,就无法找出解释它的最佳方法

The structure you desire is pretty standard practice. 您想要的结构是相当标准的做法。 It's quite possible! 很有可能!

Which Eloquent relationship you'd use depends on the direction of the relationship. 您将使用哪种雄辩的关系取决于关系的方向。 Each Stock has one Format (one-to-one). 每个Stock都有一种Format (一对一)。 But each Format can be assigned to multiple Stock (one-to-many). 但是每种Format都可以分配给多个Stock (一对多)。

For the former, your Stock Eloquent model would have a hasOne() one-to-one relationship. 对于前者,您的Stock hasOne()模型将具有hasOne()一对一关系。

class Stock extends Eloquent {

    public function format()
    {
        return $this->hasOne('Format');
    }
}

For the latter, your Format eloquent model would have a hasMany() one-to-many relationship. 对于后者,您的Format雄辩模型将具有hasMany()一对多关系。

class Format extends Eloquent {

    public function stock()
    {
        return $this->hasMany('Stock');
    }
}

Note that having both of these defined is totally acceptable and normal. 请注意,将这两个定义都完全可以接受并且是正常的。 It really just depends on which direction you need your relationship to go. 这实际上取决于您需要与您的关系发展的方向。 If you never need to look up what Stock belongs to a specific Format , you don't need the one-to-many relationship. 如果您不需要查找什么Stock属于特定Format ,则不需要一对多关系。

Also note that you may need to add a column key parameter if your column names are not easily guessable by Eloquent. 还要注意,如果您的栏名不容易被Eloquent猜中,则可能需要添加一个列键参数。 Eg: 例如:

return $this->hasOne('Format', 'my_format_id');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM