【问题标题】:Categories and Sub Categories Query?分类和子分类查询?
【发布时间】:2015-11-10 02:24:22
【问题描述】:

我正在尝试建立一个数据库,以便我可以查询它并获取一个类别的所有产品并查询它的特定子类别。

我有一张产品表

id | title | category_id (fk)

还有一个分类表:

id | title | parent

如果类别看起来像这样:

id | title | parent
1  | books | null
2  | crime | 1
3  | spy   | 2
4  | dvd   | null
5  | cd    | null

和产品:

id | title | category_id (fk)
1  | 007   | 3
1  | Murder| 2

一种产品属于一个类别。上面的“007”产品属于“间谍”子类别。 “谋杀”属于“犯罪”子类别。两者都属于父“书籍”类别。

我将如何查询数据库:

  1. 获取子类别的所有产品(例如,对于间谍,我会得到“007”)

  2. 获取父类别的所有产品,所以如果我想要书籍的所有产品,我会得到“007”和“Murder”。

【问题讨论】:

标签: laravel laravel-5 eloquent laravel-5.1


【解决方案1】:

您可以找到父类别的所有子类别,然后使用它来获取相关产品。下面的解决方案假设您描述的每个表都有 Eloquent Models,因此是 CategoryProduct 模型。

Product 模型不需要任何额外的代码,它只需要存在即可。 Category 模型必须如下所示:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    public function products()
    {
        // Build an array containing the parent category ID and all subcategory IDs found
        $categoryIds = array_merge([$this->id], $this->subcategoryIds());

        // Find all products that match the retrieved category IDs 
        return Product::whereIn('category_id', $categoryIds)->get();
    }

    protected function subcategoryIds($id = null, &$ids= [])
    {
        // If no ID is passed, set the current model ID as the parent
        if (is_null($id)) {
            $id = $this->id;
        }

        // Find subcategory IDs
        $categoryIds = $this->query()->where('parent', $id)->lists('id');

        // Add each ID to the list and recursively find other subcategory IDs
        foreach ($categoryIds as $categoryId) {
            $ids[] = $categoryId;
            $ids += $this->subcategoryIds($categoryId, $ids);
        }

        return $ids;
    }
}

现在要查找Books类别中的产品,您只需通过id查找并在模型上调用products方法即可:

$products = App\Category::find(1)->products();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 2013-06-09
    • 1970-01-01
    相关资源
    最近更新 更多