【问题标题】:How can I check if a primary key value exists in another table or not?如何检查另一个表中是否存在主键值?
【发布时间】:2021-02-11 10:44:49
【问题描述】:

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

尝试使用以下代码,但我认为这不是正确的方法。谁能给点建议...

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{
        //
    }
}

【问题讨论】:

    标签: laravel exists


    【解决方案1】:

    您可以使用exists 检查记录的关系是否存在(或存在)。

    假设您的 Country 模型上有一个名为 states 的关系:

    public function states
    {
      return $this->hasMany(State::class);
    }
    

    您可以检查Country 在您的数据库中是否有任何与之相关的States

    // returns true if there are related states, otherwise false
    Country::first()->states()->exists();
    

    您可以使用任何您想要的过滤条件,因此您可以使用find($id)where('field', $value) 等而不是first()

    【讨论】:

      【解决方案2】:

      这里使用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{
              //
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-12
        • 1970-01-01
        • 1970-01-01
        • 2020-08-23
        • 2021-06-19
        • 2021-10-27
        相关资源
        最近更新 更多