首页 > 解决方案 > 如何检查另一个表中是否存在主键值?

问题描述

我在多个表中有 id(主键),country我想检查它的值是否存在于另一个引用的表中。

尝试使用以下代码,但我认为这不是正确的方法。任何人都可以请建议一些东西...

public function check($id)
{
    $state = State::pluck('country_id');
    $country = DB::select("select count(*) from country where ? not in (?)",[$id,$state]);

    if($country == 0)
    {
        //
    }
    else{
        //
    }
}

标签: laravelexists

解决方案


在此处使用Exists方法

public function check($id)
{
    $state = State::pluck('country_id');
    $country = DB::table('country') //table set
       ->whereIn('column_name',$state) //if array then used whereIn method
       ->where('column_name',$id) //if single value use where method
       ->exists();         

    if($country)
    {
        //
    }
    else{
        //
    }
}

推荐阅读