【问题标题】:Create an array with two fields from two diferent datatables使用来自两个不同数据表的两个字段创建一个数组
【发布时间】:2019-01-25 20:38:27
【问题描述】:

我有一个问题,这是我来自 Controller 的代码:

public function searchResponse(Request $request){
        $query = $request->get('term','');
        $countries=\DB::table('countries');
        if($request->type=='countryname'){
            $countries->where('name','LIKE','%'.$query.'%');
        }
        if($request->type=='country_code'){
            $countries->where('sortname','LIKE','%'.$query.'%');
        }
           $countries=$countries->get();        
        $data=array();
        foreach ($countries as $country) {
                $data[]=array('name'=>$country->name,'sortname'=>$country->sortname);
        }
        if(count($data))
             return $data;
        else
            return ['name'=>'','sortname'=>''];
    }

此代码创建了一个稍后使用的数组,但我需要创建一个数组,该数组将列出所有国家/地区名称并在第二列中列出它们的代码,但在我的情况下,county_codes 与国家/地区名称不在同一个表中(所以我有一个1. 带有列的表 - Id 和 name,以及第二个 ID 名称为 country_id 的表(子类别表),它们通过关系连接。如何使用上面的代码来处理呢? 我的国家模型:

class Country extends Model {

  public function countries()
  {
    return $this->hasMany(Sortname::class);
  }

我的排序名称(国家代码)型号:

protected $fillable = [
      'country_id', 'title'
  ];

  public function country()
  {
    return $this->belongsTo(Country::class);
  }

因此,在子类别表中,有一列 country_id 与国家代码名称相关联。谢谢你的帮助! :)

【问题讨论】:

  • 您的 $countries 集合来自 Country 模型,但是您尝试在 foreach 中使用 $country->sortname 关系(来自 Sortname 模型)。尝试改用 $country->countries->toArray() (顺便说一下,您可能想将其重命名为 'sortnames')。 toArray() 也是可选的。

标签: php laravel


【解决方案1】:

你可以像这样使用join

$countries=\DB::table('countries')->join('country_code','country_code.country_id','countries.id')->select('countries.name','country_code.sortname');

在你写的部分

$countries=\DB::table('countries');

从这里你也不需要编写 foreach 循环来制作数组

【讨论】:

  • 但 country_code 在不同的表中,$countries=\DB::table('countries'), $country_code=\DB::table('country_code')
  • 当你需要一个连接关系来从两个不同的表中获取数据时。根据您的描述,您在 country_code 表中有 country_id 作为两个表之间的关系,您可以查看 laravel join
猜你喜欢
  • 2016-08-21
  • 1970-01-01
  • 2017-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-30
相关资源
最近更新 更多