1

如何在 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类别属性表上,我认为这不是正确的方法。

4

3 回答 3

2

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();
}
于 2019-09-14T05:30:26.163 回答
0

你不能这样。如果要访问项目使用属性。然后根据您的要求检查我提到的以下步骤。

Category.php 模型

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

Property.php 模型在这里你做错了。您可以直接访问它,您必须先与类别建立关系,然后从类别中获得项目。

属性属于类别

public function categories(){
    return $this->belongsTo('App\Category','category_id','id');
}

现在,如果您想从控制器访问它,那么您可以使用 with();

$property = Property::with('categories.project')->first();

在这里你会得到$property->categories->project->name

注意:如果你想从项目中获取属性,那么你可以使用hasOneThrough但你不能做到逆关系。

于 2019-09-14T05:43:46.663 回答
0

你的属性belongsTo不正确。属性属于类别。

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

现在您可以从以下属性中获取项目:

{{ $property->category->project->project_attribute }} 
于 2019-09-14T04:48:11.800 回答