表格结构
--------------------------
|id name parent_id
--------------------------
|1 Memory NULL
|2 RAM 1
我的功能和子功能我的模型如下
class Feature extends Model
{
public $fillable = ['name','parent_id'];
public function parent()
{
return $this->belongsTo('App\Feature','parent_id');
}
public function child()
{
return $this->hasMany('App\Feature','parent_id');
}
}
现在我想获取父功能和子功能,
答案 0 :(得分:1)
试试这个:
$f = Feature::with('child', 'parent')->get()
现在你可以这样:
$f->name;
$f->parent->name;
$f->child->name;
答案 1 :(得分:1)
$features = Feature::whereNull('parent_id')->with('child')->get();
然后
foreach ($features as $feature)
{
$feature->name; // Parent
$feature->child->name; // Child
}