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!
CodePudding user response:
See this lib: https://github.com/staudenmeir/eloquent-has-many-deep
Examples in README.md.
CodePudding user response:
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);
}
CodePudding user response:
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);
}
}