Laravel 获取类别和子类别
Laravel fetch category and sub-category
Table结构
--------------------------
|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');
}
}
现在我想获取父特征和子特征,
试试这个:
$f = Feature::with('child', 'parent')->get()
现在你可以像这样拥有它们了:
$f->name;
$f->parent->name;
$f->child->name;
$features = Feature::whereNull('parent_id')->with('child')->get();
然后
foreach ($features as $feature)
{
$feature->name; // Parent
$feature->child->name; // Child
}
Table结构
--------------------------
|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');
}
}
现在我想获取父特征和子特征,
试试这个:
$f = Feature::with('child', 'parent')->get()
现在你可以像这样拥有它们了:
$f->name;
$f->parent->name;
$f->child->name;
$features = Feature::whereNull('parent_id')->with('child')->get();
然后
foreach ($features as $feature)
{
$feature->name; // Parent
$feature->child->name; // Child
}