[英]Laravel groupBy on relationship without array_merge
我正在構建一個 Laravel 9 項目。 我創建了Product
model 和ProductOption
model。我的選項需要按名為region_code
的列(並不總是設置)分組,以便可以輕松顯示產品的選項。 我意識到如果我運行$product->options->groupBy('region_code')
它會給我想要的結果,但我需要這些分組選項成為Product
model 的一部分,因此我正在做一個array_merge
。
這種方法有效,但我覺得必須將其轉換為數組並將結果合並回一個數組有點麻煩。
我確實嘗試在我with
子句中執行groupBy('region_code')
,但這並沒有給我任何東西。
這是我當前的代碼和 output
$selectedProduct = $request->input('product');
$selectedType = $request->input('type');
$product = Product::where('slug', $selectedProduct)
->where('is_enabled', true)
->with(['options' => function ($query) use ($selectedType) {
$query->where('is_enabled', true)
->whereNotNull('region_code')
->where('slug', 'like', "%$selectedType%");
}])->first();
if (! $product) {
return response()->json([
'message' => "No product found."
], 404);
}
$product = array_merge($product->toArray(), [
'options' => $product->options->groupBy('region_code')->toArray()
]);
return response()->json([
'product' => $product
], 200);
一種更簡潔的方法,我認為我可以覆蓋options
鍵,然后執行以下操作:
$options = $product->options->groupBy('region_code');
$product->options = $options;
return response()->json([
'product' => $product
], 200);
但這會完全失去分組。
我該如何清理它?
下面是每個 model 的表架構:
Product
Schema::create('products', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('title');
$table->string('slug')->unique();
$table->string('description')->nullable();
$table->json('extra')->nullable();
$table->boolean('is_enabled')->default(1)->index();
$table->timestamps();
$table->softDeletes();
});
ProductOption
Schema::create('product_options', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignUuid('product_id');
$table->string('title');
$table->string('slug')->unique();
$table->string('description')->nullable();
$table->string('region_code')->nullable()->index();
$table->json('extra')->nullable();
$table->string('stripe_id')->unique();
$table->integer('quantity')->default(1);
$table->boolean('is_enabled')->default(1)->index();
$table->timestamps();
$table->softDeletes();
});
$selectedProduct = $request->input('product');
$selectedType = $request->input('type');
$product = Product::where('slug', $selectedProduct)
->where('is_enabled', true)
->with(['options' => function ($query) use ($selectedType) {
$query->where('is_enabled', true)
->whereNotNull('region_code')
->where('slug', 'like', "%$selectedType%")
//just add here
->groupBy('region_code');
}])->first();
if (!$product) {
return response()->json([
'message' => "No product found."
], 404);
}
return response()->json([
'product' => $product
], 200);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.