2017-07-02 173 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;