'Version → (many to many) → Function → (belongs to) → Category
I have following table layouts:
functions:
- id
- name
- category_id
categories:
- id
- name
versions:
- id
- name
function_version
- function_id
- version_id
I would like to call the following relationships
From version model $version->categories
From category model $category->versions
Thanks for your help!
Solution 1:[1]
Solution 2:[2]
As laravel explain Laravel Relationships in their docs, for many to many you can use this code
public function 'function name'()
{
return $this->belongsToMany(App Model Name::class);
}
Solution 3:[3]
try below code:
From version model:
$version = Version::with('functions' => function($query) { $query->withCount('category'); })->firstOrFail(); return $version->functions->category_count;From category model:
$category = Category::with('functions' => functions($query) { $query->withCount('versions'); })->firstOrFail(); return $category->functions->versions_count;
for above code you have below relationship in particular model:
class Category extends Model
{
public function functions()
{
return $this->hasMany(Function::class);
}
}
class Function extends Model
{
public function Category()
{
return $this->belongsTo(Category::class);
}
public function versions()
{
return $this->belongsToMany(Version::class);
}
}
class Version extends Model
{
public function functions()
{
return $this->belongsToMany(Function::class);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rollsover |
| Solution 2 | Mansjoer |
| Solution 3 |
