【问题标题】:related records of parent table in many to many relation in laravellaravel中多对多关系中父表的相关记录
【发布时间】:2019-02-23 05:01:35
【问题描述】:

表一:categories: id,name,parent_id

id   name        parent_id
1    Vehicle     null
2    Car         1
3    Sedan       2

Vehicle > Car > Sedan

表2:features: id, name

id   name 
1    type
2    cylinder
3    color
4    weight

表 3:category_feature: category_id, feature_id

category_id  feature_id
1            1
1            2
2            3
3            4

我可以按父级(类别)获取所有功能。

例如:

类别型号:

public function features()
{
    return $this->belongsToMany(Feature::class);
}

还有:

$category = Category::find(1);
$features = $category->features()->get(); 

如何按子类别获取 孩子的所有特征和父亲类别的特征?

类似这样的:

$category = Category::find(3);
$features = $category->parent_features()->get();

我希望它返回这些:类型、圆柱体、颜色、重量

【问题讨论】:

  • 如何``` $category = Category::find(3); $features = $category::with('hasParent')->features()->get(); ``` 假设您在类别中设置了关系以检查它是否有父对象。

标签: laravel eloquent many-to-many


【解决方案1】:

关于类别模型:

public function parent(){
    return $this->belongsTo(\App\Category::class);
}

然后你就可以一次性加载了:

$category = Category::with(['features', 'parent' => function($query){
     $query->with('features');
}])->find(3);

然后就可以拉取父母的特征了:

$features = $category->parent->features;

或者原车的特点:

$originalFeatures = $category->features;

【讨论】:

  • 谢谢。我检查了你的代码。 $category->parent->features 只返回第一个父特征。 $category->features 返回空值。所以我错过了当前类别和根类别的特征。
猜你喜欢
  • 2015-09-11
  • 2016-10-28
  • 2014-09-24
  • 2021-08-21
  • 1970-01-01
  • 2014-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多