首页 > 解决方案 > php变量和变量赋值返回的值不同

问题描述

我正面临一个非常奇怪的问题。问题很快:

$x = some_object;
return response()->json($x)            =>  {}  
return response()->json(some_object)   =>  {some_object}

这是所有代码(代码在 else 语句中):

public function checkCalls(Request $req)
{
    $active_call = VideoCall::where("receiver_id", (int) $req->input("user_id"));

    if ($active_call->where("call_situation", "call")->exists()) {
        $active_call = $active_call->first();

        $caller_id = $active_call->caller_id;
        $caller = User::where("id", $caller_id)->first();
        $caller_name = $caller->name;
        $caller_img = $caller->image;
        return response()->json([
            "friend" => $caller_id,
            "caller_name" => $caller_name,
            "caller_img" => $caller_img
        ]);
    } else if ($active_call->where("call_situation", "yes")->exists()) {
        return response()->json("gorusme yapıyor");
    } else if ($active_call->where("call_situation", "decline")->exists()) {
        $caller_id = $active_call->where("call_situation", "decline")->first()->caller_id;
        return response()->json("arama red edildi", $caller_id);
    } else {
        return response()->json("arama yok"); 
        //this code runs, I m changing here to get different returns  
    }
}

当我在 else 括号内更改时,返回true

return response()->json(VideoCall::where("receiver_id", (int) $req->input("user_id"))->exists());

但这会返回false

return response()->json($active_call->exists());

$active_call由于某种原因返回一个空对象。唯一的解释是括号的$active_call变化,if()但我找不到任何可以改变它的东西。那么为什么会这样呢?

*编辑:使问题更清晰,添加了问题的较短版本。

*编辑 2:else 语句中的代码正在运行。我正在更改该 return 语句以获得不同的结果

标签: phpmysqllaravelvariables

解决方案


这是因为您$active_call在函数中重新分配:

$active_call = $active_call->first();

它不再是 a Builder,而是 a VideoCall

所以,这一行:

return response()->json($active_call->exists());

实际上是:

return response()->json(VideoCall::where("receiver_id", (int) $req->input("user_id"))->first()->exists());

注意额外的->first()


推荐阅读