【问题标题】:Laravel realationship find root parentLaravel 关系找到根父级
【发布时间】:2021-04-24 12:01:45
【问题描述】:

我有categories 表结构类似:

id
title
category_id

类别模型关系:

public function categories()
{
    return $this->hasMany(Category::class);
}

public function subcategories()
{
    return $this->categories()->with('subcategories');
}

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

示例表数据:

{
    "id": 1,
    "title": "Product Categories Group",
    "category_id": null
},
{
    "id": 2,
    "title": "Buy",
    "category_id": 1
},
{
    "id": 3,
    "title": "Sale",
    "category_id": 1
},
{
    "id": 4,
    "title": "Fruits",
    "category_id": 2
},
{
    "id": 5,
    "title": "Apple",
    "category_id": 4
}

在这种情况下,我如何使用 id 检查父类别是 Buy 类别或 Sale。例如如何检查Apple 类别父是BuySale 类别?

【问题讨论】:

    标签: mysql database laravel eloquent relationship


    【解决方案1】:

    你可以使用while循环,直到找到父级

    试试这个

    $category = Category::where('title', 'Apple')->firstOrFail();
    if (!$category->category_id) {
            $parentCategory = $category;
    }
    while (isset($category->category_id)) {
        $category = Category::find($category->category_id);
    }
    
    return $parentCategory;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-05
      • 1970-01-01
      • 2018-06-17
      • 2023-02-08
      • 2018-02-17
      • 2021-09-09
      • 2022-01-01
      相关资源
      最近更新 更多