laravel - 如何检查另一个表中是否存在主键值?
问题描述
我在多个表中有 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{
//
}
}
解决方案
在此处使用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{
//
}
}
推荐阅读
- c - 使用管道时似乎无法打印子进程的标准输出(C 和 Windows)
- scala - 如何在 Scala 中过滤掉字符串向量中的一次出现?
- java - 我可以在不手动下载二进制文件的情况下运行 PhantomJS 吗?
- python-3.x - 将Django中的对象列表序列化为嵌套的json
- c++ - 向量是否也在 C++ 中初始化原始类型?
- clojure - Luminus H2留言簿应用程序中没有合适的驱动程序
- python - 在 Notebook Python 中禁用 tesseract 字典
- javascript - 对象没有被传递到本地存储 - React JS
- php - 在灵活的列中显示数据,而不是在 php 中的行
- reactjs - 反应排序列表 - 点击事件触发不正确