类别和子类别查询?

时间:2015-11-09 17:19:00

标签: laravel laravel-5 eloquent laravel-5.1

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

我有产品表

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'之上产品属于' Spy'子类别。 '谋杀'属于' Crime'子类别。两者都属于父母的书籍。类别。

我如何查询数据库:

  1. 获取子类别的所有产品(例如间谍我会得到' 007')

  2. 获取所有产品的父类别,所以如果我想要所有产品的书籍,我会得到' 007'和'谋杀'

1 个答案:

答案 0 :(得分:0)

您可以找到父类别的所有子类别,然后使用它来获取相关产品。下面的解决方案假设您为所描述的每个表都有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();
相关问题