php - 我通过 sql 从数据库中获取所有值
问题描述
所以,我有一个countries
带有一列的表flag.
在这里我有每个国家/地区的代码。我试图通过 SQL 查询在我的页面中加入表,但是我有这个......而且我只需要显示正确的标志,根据国家/地区的 id,不是所有的标志。
https://imgur.com/a/2F6Qvdv
我的数据库结构:表、countries
列和id
country
flag
这是我的代码:
控制器:
$data['contact_users'] = DB::table('contacts')
->join('users', 'users.id', '=', 'contacts.contact_id')
->join('industries', 'industries.id', '=', 'users.industry_id')
->join('countries', 'countries.id', '=', 'users.country_id')
->join('organization_types', 'organization_types.id', '=', 'users.organization_type_id')
->join("role_users", "role_users.user_id","=","users.id")
->leftJoin("career_paths", "career_paths.user_id","=","users.id")
->select('users.*', 'industries.industry', 'countries.country', 'organization_types.organization_type', "role_users.role_id", 'career_paths.function_id')
->where('contacts.contact_id', '!=', $id)
->where('users.deleted_at', '=', null)
->whereIn('contacts.user_id', $contact_id)
->whereNotIn('contacts.contact_id', $contact_id)
->whereNotIn('contacts.contact_id', $inviter_id)
->groupBy('contact_id')
->take(4)
->get();
$flags = DB::select('SELECT flag FROM countries WHERE country = "India"');
看法:
@foreach ($flags as $flag)
{{ $contact->country }} <span class="{{ $flag->flag}}"></span>
@endforeach</a><br>
我得到{{ $contact->country }}
了国家的名字,得到了国家{{ $contact->id }}
的 id。我怎样才能在 id 和 flag 列之间建立连接?
解决方案
// 试试这个。你应该在这里有两张桌子,因为你提到了加入两张桌子之类的东西。样本数据和查询。
countries: id | country | flagid
---|---------|----
1 | US | 1
flag: id | flag
----------
1 | image
//控制器。此代码假设您正在选择/输入国家/地区名称
public function getSingleFlag(Request $request)
{
$country = $request->input('countryname')
$data['country']=DB::table('countries')
->leftjoin('flag','countries.flagid','=','flag.id')
->where('country',$country)
->first();
return view('form',$data)
}
//此代码假设您没有选择/输入国家名称。您只想显示具有相应标志的所有国家/地区
public function getAllFlag()
{
$data['country']=DB::table('countries')
->leftjoin('flag','countries.flagid','=','flag.id')
->get();
return view('form',$data)
}
//your blade.
//for the first function
<p> {{ $country->country }} - {{ $country->flag}}</p>
//for the second function use foreach
@foreach($country as $c)
<p> {{ $c->country }} - {{ $c->flag}}</p>
@endforeach
注意:记得使用你的图片标签来展示你的旗帜。只是让您了解如何实现
推荐阅读
- android-studio - 看不到 Android Studio 但已安装
- epson - linux上EPSON JPOS日志跟踪文件轮换策略
- mysql - 无法从 EC2 实例的公共 IP 连接 AWS RDS MySQL
- ansible - 将后缀/前缀添加到单个 ansible 变量
- c# - Linq Left Join 引发错误,提示“已经有一个打开的 DataReader 与此连接关联,必须先关闭。”
- linux - makefile 中“ifeq (a,$(wildcard .a))”的目的是什么?
- bash - 删除与 grep 模式匹配的行
- python - SageMaker TF 2.3 分布式训练
- vue.js - 为电子Vue应用程序实现动态主题系统
- c - C 我可以返回数组而不是指针吗?如果不能,我可以使用指针吗?