【发布时间】: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() 也是可选的。