2015-02-07 107 views
0

我開發與4數據庫表Laravel 4應用:正確使用雄辯關係

  • 治療師
  • TherapistType

我使用外鍵引用其他表中的數據。 的關係如下:

  • 治療師可以有一個治療師型,市,縣
  • 治療師型,直轄市可以屬於很多治療。
  • 一個自治市可以有一個縣。
  • 一個縣可以屬於許多市鎮和治療師。

我正在使用雄辯的ORM。

這是我嘗試使用代碼:

治療師型號:

public function therapistType() { 
     return $this->belongsTo('TherapistType'); 
    } 

    public function municipality() { 
     return $this->hasOne('Municipality'); 
    } 

    public function county() { 
     return $this->hasOne('County'); 
    } 
} 

市型號:

public function county() { 
     return $this->hasOne('County'); 
    } 

在我控制我用下面的代碼來獲取治療:

$therapists = Therapist::paginate(10); 
return View::make('index', compact('therapists')); 

最後在我看來,這就是我想獲得相應的治療類型,治療師:

<span class="therapisttype">{{{ $therapist->therapistType }}}</span> 

但是我沒有得到任何數據。

我在做什麼錯?

+0

什麼是引用'TherapistType'的外鍵列被調用?它應該是'therapist_type_id'。如果不是,你需要傳遞名字作爲第二個參數到'belongsTo()' – lukasgeiter 2015-02-07 23:47:44

+0

我不知道這一點,謝謝!但現在我又遇到了另一個問題。我有三種治療師類型,它只返回頭三名治療師的數據。它也無視治療師將外鍵分配給治療師(它應該是所有治療師的第一種治療師類型)並列出所有治療師。 – PeterInvincible 2015-02-08 00:07:14

+1

嘗試做@Victor建議並回應「TherapistType」的實際屬性。 '{{$治療師 - >治療師類型 - >名稱}}' – lukasgeiter 2015-02-08 00:10:58

回答

2

$therapist->therapistType應該返回一個對象,但是你沒有迴應該對象的屬性。讓我們想象一下therapistType表有name屬性,那麼你應該做

{{$therapist->therapistType->name}}如果你想回顯那個名字。

我將從var_dumping對象開始,您可以使用$therapist->therapistType假設您已正確設置關係,您應該能夠看到它的所有屬性。

希望它有幫助。