2017-07-02 14 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; 
関連する問題