I have requests table that belongs to subcategories table which belongs to categories table, so from Request model how can I get an attribute from categories?
JavaScript
x
tables
->requests
id
name
subcategory_id
->subcategories
id
name
category_id
->categories
id
name
color
So I need to get color from Request model, I already have the tree models created
JavaScript
class Request extends Model
{
public function user()
{
return $this->belongsTo(User::class)->get();
}
public function color()
{
$somemagicstuff;
return $color;
}
}
Advertisement
Answer
You need to define your relationships:
JavaScript
# Request.php
class Request extends Model
{
public function subcategory()
{
return $this->belongsTo(Subcategory::class);
}
}
–
JavaScript
# Subcategory.php
class Subcategory extends Model
{
public function category()
{
return $this->belongsTo(Category::class);
}
}
Then you could just do:
JavaScript
$color = Request::first()->subcategory->category->color;
Of course, you can add a computed attribute to your Request
class to easy access (keep in mind that this could increase the number of queries):
JavaScript
# Request.php
class Request extends Model
{
public function subcategory()
{
return $this->belongsTo(Subcategory::class);
}
public function getColorAttribute()
{
return $this->subcategory->category->color;
}
}
Then:
JavaScript
$color = Request::first()->color;