DB的空字符串为null ??? if($ var === null){语句}

问题描述 投票:0回答:2

如果有记录,我正在检查数据库。如果没有,我想做一个。但是我不能从数据库中得到NULL,我得到了空字符串。我该如何解决?

public function chechk_slots(){
    $character_id = Auth::user()->id;
    $inv_user = DB::table("slots")->where('character_id', $character_id)->get();
    return $inv_user?? null ;
}

public function to_inventary()
{

    $a = "Is record";
    $b = "there is no record";

    $character_id = Auth::user()->id;
    $inv_items = DB::table("items_chars")->where('character_id', $character_id)->get();
    $user_profile = $this->show_profile();
    $slot = $this->chechk_slots();
    //dd($slot);
    //DB::table("slots")->insert(['character_id' => $character_id]);
   // dd($slot[0]->character_id);
    if($slot === null){
        dd($b);
        DB::table("slots")->insert(['character_id' => $character_id]);
    }
    else{
        dd($a);
    }
    //return view('inventary', compact('user_profile', 'inv_items'));
}

我在DB图片中的表“在此处输入图像描述”没有记录如果我dd($ slot);我得到了这张图片“在此处输入图像描述”

所以空字符串!= null并且无法获取记录...我该如何更改?

laravel null isset is-empty
2个回答
0
投票

问题1-收集

即使没有数据,您也会获得一个集合。

$inv_user = DB::table("slots")->where('character_id', $character_id)->get();

问题2-空合并

它类似于三元运算符,但其行为类似于左侧操作数上的isset,而不仅仅是使用其布尔值。

$inv_user = DB::table("slots")->where('character_id', $character_id)->get();

return $inv_user ?? null;

[$inv_user分配为Illuminate\Support\Collection


解决方案

使用count()和三元运算符。

public function chechk_slots(){
    $character_id = Auth::id();
    $inv_user = DB::table("slots")->where('character_id', $character_id)->count();

    return $inv_user ?: null ;
}

-1
投票

您可以使用laravel的雄辩功能firstOrCreatefirstOrNew

它将根据查询来检查数据库中的记录,如果找到则返回或插入一个。如果您不想插入新的或返回该记录。您也可以使用updateOrCreate

更多请参阅此内容:Laravel Different Creations Methods

希望这会有所帮助:)

© www.soinside.com 2019 - 2024. All rights reserved.