需求:用户资料展示原因文本而非ID,现有接口仅返回ID问题排查
Let's break down what's going wrong with your current code and fix it so you can show actual reason text (not just IDs) in the user profile.
What's Off in the Current Code?
Your existing query for $reasondisplay has a syntax issue that's blocking it from fetching the right data:
- The line
Reason::where("$reasons", '=', 'id')is incorrect.$reasonsis a collection of IDs, so you need to usewhereIninstead ofwhereto match multiple IDs at once. - Converting the
$reasonscollection to a string ("$reasons") doesn't work as a column name here—you want to match against theidcolumn of theReasontable.
Corrected Code
Here's the fixed version of your endpoint, with comments explaining the changes:
public function getreason(Request $request){ // Get all reason IDs linked to the given trade_id $reasons = TradeReason::where('trade_id', $request->trade_id)->pluck("reason_id"); // Fetch corresponding reason texts using whereIn to match multiple IDs // Add a check to avoid running an empty query if no reasons exist $reasondisplay = $reasons->isNotEmpty() ? Reason::whereIn('id', $reasons)->pluck("reason") : collect(); // Return empty collection if no reasons found return response()->json($reasondisplay); }
Bonus: Clean Up with Model Relationships
If you haven't already, defining a relationship between TradeReason and Reason makes this code even cleaner and more maintainable.
First, add this to your TradeReason model:
public function reason() { return $this->belongsTo(Reason::class, 'reason_id'); }
Then rewrite your endpoint to eager load the related reasons directly:
public function getreason(Request $request){ $reasondisplay = TradeReason::where('trade_id', $request->trade_id) ->with('reason') // Eager load the related Reason model ->get() ->pluck('reason.reason'); // Extract only the reason text return response()->json($reasondisplay); }
This approach follows Laravel's best practices for working with related models and keeps your code concise.
内容的提问来源于stack exchange,提问作者user9752285

