我想在用户个人资料中显示原因,但在用户个人资料中显示原因ID

时间:2018-05-07 11:00:57

标签: laravel

public function getreason(Request $request){

    $reasons = TradeReason::where('trade_id',$request->trade_id)->pluck("reason_id");

    $reasondisplay = Reason::where "$reasons", '=', 'id')->pluck("reason");

    return response() -> json($reasondisplay);
}

其代码仅显示原因ID但未在用户个人资料中显示原因

3 个答案:

答案 0 :(得分:1)

您正在查询ID为$reasondisplay的数组。您必须使用whereIn()函数来查询数组中的id并获取原因。

public function getreason(Request $request){

    $reasons = TradeReason::where('trade_id',$request->trade_id)->pluck('reason_id');

    $reasondisplay = Reason::whereIn('id', $reasons)->pluck('reason');

    return response() -> json($reasondisplay);
}

您可以参考laravel Documentation

答案 1 :(得分:0)

您的功能未正确编码,因此只需使用此代码替换您的函数,并使用whereIn()方法代替where

public function getreason(Request $request){

    $reasons = TradeReason::where('trade_id',$request->trade_id)->pluck("reason_id");

    $reasondisplay = Reason::whereIn('id',$reasons)->pluck("reason");

    return response()->json($reasondisplay);
}

答案 2 :(得分:0)

列必须是函数

中的first参数
public function getreason(Request $request){
    $reasons = TradeReason::where('trade_id',$request->trade_id)->first();
    $reason = "";
    if($reasons){
        $reasondisplay = Reason::find($reasons->reason_id)->first();
        if($reasondisplay){
            $reason = $reasondisplay->reason;
        }
    }
    return response()->json(["reason"=>$reason]);
}

最好你可以use relation

在TradeReason

public function reason()
{
    return $this->hasOne('App\TradeReason','id','reason_id');
    //                                      ^      ^
    //                                      |      |____ 'local_key'
    //                                      |__'foreign_key'
}

在控制器

public function getreason(Request $request){
    $reason = "";
    $tr = TradeReason::where('trade_id',$request->trade_id)->with("reason")->first();
    return response()->json(["reason"=>$tr->reason->reason]);
    //                                       ^          ^
    //                                       |          |___Column Name
    //                                       |__Relation Name
}
相关问题