我想從 UserController 顯示用戶使用了多少產品和用戶資訊。我Resources為它創建了兩個。所以我使用$idHere is My UserControllercode搜索他
public function show($id)
{
//
$user = User::find($id);
if (is_null($user)) {
return response()->json([
'message' => 'User Not Found',
'status' => 404
], 404);
}
$products = Product::where('user_id', $user->id)->get();
return response()->json([
'data' => new UserProductResource($products),
'status' => 200
], 200);
}
這是我的 UserProductResource
<?php
namespace App\Http\Resources;
use App\Http\Resources\ProductResource;
use Illuminate\Http\Resources\Json\JsonResource;
class UserProductResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'first_name' => $this->first_name,
'last_name' => $this->last_name,
'profile_img' => $this->profile_img,
'products' => ProductResource::make($this->products),
];
}
}
錯誤是 ![此集合實體上不存在屬性 [id]?](https://img.uj5u.com/2021/11/21/060b69f340734667bae28d6085f3a450.png)
我的路線是:
Route::get('/show-product/{id}', [UserController::class, 'showProduct']);
uj5u.com熱心網友回復:
試試這個解決方案:
您在此查詢中有錯誤
$products = Product::where('user_id', $user_id)->get();
因為 $user_id 是 User 的物件,而不是單個值。
您的代碼:
public function show($id)
{
//
$user_id = User::find($id);
if (is_null($user_id)) {
return response()->json([
'message' => 'User Not Found',
'status' => 404
], 404);
}
$products = Product::where('user_id', $user_id)->get();
return response()->json([
'data' => new UserProductResource($products),
'status' => 200
], 200);
}
新代碼:
public function show($id)
{
//
$user = User::find($id);
if (is_null($user)) {
return response()->json([
'message' => 'User Not Found',
'status' => 404
], 404);
}
$products = Product::where('user_id', $user->id)->get();
return response()->json([
'data' => new UserProductResource($products),
'status' => 200
], 200);
}
uj5u.com熱心網友回復:
find($id) 回傳一個物件,因此您不能在 where() 中傳遞物件。替換您的以下行
$products = Product::where('user_id', $user_id)->get();
用這條線
$products = Product::where('user_id', $user_id->id)->get();
它會起作用。
uj5u.com熱心網友回復:
new UserProductResource($products)
這里的產品物件在資源檔案中傳遞,如果我們檢查 UserProductResource 中的欄位,它們看起來像 User 模型中存在的欄位。
$products 是否有類似產品的欄位或關系?
$products 是一個集合,因此應該使用 UserProductResource::collection()。
理想情況下,您應該在用戶和產品之間建立關系并執行此操作
$user = User::with('products')->find($id);
if (is_null($user_id)) {
return response()->json([
'message' => 'User Not Found',
'status' => 404
], 404);
}
return response()->json([
'data' => new UserProductResource($user),
'status' => 200
], 200);
由于 UserProductResource 中可以有多個產品,因此您可以執行此操作
'products' => ProductResource::collection($this->products),
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/361934.html
