0
我有以下結構(不可編輯)在我的數據庫:laravel一對多/屬於關聯
-- Table 'computers'
---------------------------
id, operatingsystems_id
-- Table 'operatingsystems'
---------------------------
id, name
一臺計算機可以有一個操作系統(一對一),但一個操作系統可以有許多計算機(一到很多)
我已經定義了以下內容,我是這樣做的錯誤方式?
class Computer {
protected $table = 'computers';
public function operatingSystem()
{
return $this->belongsTo('OperatingSystem', 'operatingsystems_id');
}
}
class OperatignSystem {
protected $table = 'operatingsystems';
public function computers()
{
return $this->hasMany('Computer', 'operatingsystems_id');
}
}
因爲問題是,當我做
Computer::find(1)->operatingSystem()->get()
我得到一個集合
不應該使用關係,並且使用belongsTo關係嗎?這就是我從文檔 – kitensei 2015-04-02 14:54:39
得知我使用hasOne,因爲我認爲它更加明確。按照你的方式,你也可以使用first()而不是get,並且你總是得到一個項目而不是一個集合。 – Shemahmforash 2015-04-02 15:13:44