首页 > 解决方案 > Laravel BelongsTo 通过关系

问题描述

如何在 Laravel 中实现 BelongsToThrough 关系?

我有表:

**projects_table**
id 

**categories_table**
id
project_id 

**properties_table**
id
category_id

类别属于项目

public function project(){
    return $this->belongsTo('App\Project');
}

属性属于类别

public function category(){
    return $this->belongsTo('App\Category');
}

我们怎样才能建立关系?

属性属于通过类别的项目

public function project(){
     return $this->belongsToThrough('App\Project', 'App\Category');
}

编辑问题。

因为我想在我的应用程序上进行多租户,而租户是 PORJECT。我想按项目分隔类别和属性。

CATEGORY 属于属于 PROJECT PROPERTY 属于属于 CATEGORY

所以我想通过 CATEGORY 建立 PROPERTY 和 PROJECT 之间的关系。现在,我需要补充:project_id类别属性表上,我认为这不是正确的方法。

标签: laravellaravel-5eloquentrelationshiproute-model-binding

解决方案


I think you can do $project->category->property as you have a one-to-one relationship between Project and Category and again a one-to-one relationship between Category and property, beside this, if you want to define a relationship between Project and Property through you may consider has-one-through relaationship.

In Project model

public function property()
{
    return $this->hasOneThrough('App\Property', 'App\Category');
}

and in Property model

public function property()
{
    return $this->hasOneThrough('App\Project', 'App\Category');
}

May be

In that case, you can also do something like

in Property model

public function project()
{    
   return $this->category->project( or projects);

   // or if Category and properties have many-to-many relationship you can do 
   return $this->categories->with('projects')->get();
}

推荐阅读