首页 > 解决方案 > 我通过 sql 从数据库中获取所有值

问题描述

所以,我有一个countries带有一列的表flag.在这里我有每个国家/地区的代码。我试图通过 SQL 查询在我的页面中加入表,但是我有这个......而且我只需要显示正确的标志,根据国家/地区的 id,不是所有的标志。 https://imgur.com/a/2F6Qvdv

我的数据库结构:表、countries列和idcountryflag

这是我的代码:

控制器:


             $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 列之间建立连接?

标签: phpdatabaselaravel

解决方案


// 试试这个。你应该在这里有两张桌子,因为你提到了加入两张桌子之类的东西。样本数据和查询。

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

注意:记得使用你的图片标签来展示你的旗帜。只是让您了解如何实现


推荐阅读