简体   繁体   中英

Laravel fetch category and sub-category

Table structure

--------------------------
|id     name    parent_id
--------------------------
|1      Memory  NULL
|2      RAM     1

for my features and sub-features my model as below

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

Now i want to fetch parent features and sub-features,

Try this :

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

now you can have them like this :

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

Then

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM