diff --git a/beike/Models/CategoryPath.php b/beike/Models/CategoryPath.php index 3f46f69b..c022e9ec 100644 --- a/beike/Models/CategoryPath.php +++ b/beike/Models/CategoryPath.php @@ -4,6 +4,7 @@ namespace Beike\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Relations\HasOne; class CategoryPath extends Model { @@ -14,4 +15,14 @@ class CategoryPath extends Model 'path_id', 'level', ]; + + public function category(): HasOne + { + return $this->hasOne(Category::class, 'id', 'category_id'); + } + + public function pathCategory(): HasOne + { + return $this->hasOne(Category::class, 'id', 'path_id'); + } } diff --git a/beike/Repositories/CategoryRepo.php b/beike/Repositories/CategoryRepo.php index b1343789..ab871ad3 100644 --- a/beike/Repositories/CategoryRepo.php +++ b/beike/Repositories/CategoryRepo.php @@ -64,16 +64,27 @@ class CategoryRepo public static function autocomplete($name) { - $categories = Category::query()->with('description') - ->whereHas('description', function ($query) use ($name) { - $query->where('name', 'like', "{$name}%"); - })->limit(10)->get(); + $categories = Category::query()->with('paths.pathCategory.description') + ->whereHas('paths', function ($query) use ($name) { + $query->whereHas('pathCategory', function ($query) use ($name) { + $query->whereHas('description', function ($query) use ($name) { + $query->where('name', 'like', "{$name}%"); + }); + }); + }) + ->limit(10)->get(); $results = []; foreach ($categories as $category) { + $pathName = ''; + foreach ($category->paths->sortBy('level') as $path) { + if ($pathName) { + $pathName .= ' > '; + } + $pathName .= $path->pathCategory->description->name; + } $results[] = [ 'id' => $category->id, - 'name' => $category->description->name, - 'image' => $category->image, + 'name' => $pathName, ]; } return $results;