laravel - 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
在类别和属性表上,我认为这不是正确的方法。
解决方案
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();
}
推荐阅读
- python - 动态分组条形图
- python - Python迭代列表日期时间值
- python-3.x - 在python中解析日期时间
- service-worker - 如果多个用户使用同一个设备怎么办?
- c - 带有 SIG_BLOCK 的 sigprocmask 不会阻止 SIGALRM
- javascript - 使用 Google Apps 脚本和 Google 课堂创建学生
- asp.net-core - Razor 页面中的路由数据
- python - 我正在尝试从 Word2Vec 词汇表中获取特定单词的键
- python - 在移动浏览器上的 Django Web App 中强制下载文件
- c - 如何从 strrchr() 或 strchr() 中提取剩余的子字符串?