2015-02-07 40 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假设您已正确设置关系,您应该能够看到它的所有属性。

希望它有帮助。