我有属于子类别表的请求表,而属于类别表,所以从请求模型中如何从类别中获取属性?
tables
->requests
id
name
subcategory_id
->subcategories
id
name
category_id
->categories
id
name
color
所以我需要从Request模型中获取颜色,我已经创建了树模型
class Request extends Model
{
public function user()
{
return $this->belongsTo(User::class)->get();
}
public function color()
{
$somemagicstuff;
return $color;
}
}
答案 0 :(得分:3)
您需要定义关系:
# Request.php
class Request extends Model
{
public function subcategory()
{
return $this->belongsTo(Subcategory::class);
}
}
-
# Subcategory.php
class Subcategory extends Model
{
public function category()
{
return $this->belongsTo(Category::class);
}
}
那你可以做:
$color = Request::first()->subcategory->category->color;
当然,您可以将计算属性添加到Request
类中以方便访问(请注意,这可能会增加查询数量):
# Request.php
class Request extends Model
{
public function subcategory()
{
return $this->belongsTo(Subcategory::class);
}
public function getColorAttribute()
{
return $this->subcategory->category->color;
}
}
然后:
$color = Request::first()->color;