正确使用雄辩的关系

时间:2015-02-07 23:43:18

标签: laravel orm eloquent relationship foreign-key-relationship

我正在开发一个包含4个数据库表的Laravel 4应用程序:

  • 治疗师
  • TherapistType

我使用外键来引用其他表中的数据。 关系如下:

  • 治疗师可以有一种治疗师类型,自治市和县
  • 治疗师类型和市政当局可以属于许多治疗师。
  • 一个市可以有一个县。
  • 一个县可以属于许多城市和治疗师。

我正在使用Eloquent 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>

但是我没有数据。

我做错了什么?

1 个答案:

答案 0 :(得分:2)

$therapist->therapistType应该返回一个对象,但是你没有回显所述对象的属性。让我们假设therapistType表具有name属性,那么您应该

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

我将从var_dumping对象开始,您可以使用$therapist->therapistType假设您已正确设置关系,您应该能够看到它的所有属性。

希望它有所帮助。

相关问题