2017-07-02 132 views
0

表结构Laravel获取类别和子类别

-------------------------- 
|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'); 
    } 
} 

现在我想取父功能和子功能,

回答

1
$features = Feature::whereNull('parent_id')->with('child')->get(); 

然后

foreach ($features as $feature) 
{ 
    $feature->name; // Parent 
    $feature->child->name; // Child 
} 
1

试试这个:

$f = Feature::with('child', 'parent')->get() 

现在你可以让他们像这样:

$f->name; 
$f->parent->name; 
$f->child->name;