对不起,我使用laravel ORM有两个json数组,如下所示:
PHP
$personnels = Personnel::all();
$skills = Languagelv::all();
return view('bs_sidebar/recommend',[
'personnels' => $personnels,
'skills' => $skills,
]);
模型
class Personnel extends Model
{
protected $table = 'personnels';
protected $fillable = ['name', 'sex'];
}
class Personnels_skill extends Model
{
public $timestamps = false;
protected $table = 'personnels_skill';
protected $fillable = ['skill_name','personnels_id'];
}
json结果
{personnels:[
{"id" : 1,"name" : "bruce","sex" : 1},
{"id" : 2,"name" : "peter","sex" : 0}
]
};
{skill:[
{"id" : 1,"skill_name": 'php', "personnels_id" : 1},
{"id" : 2,"skill_name": 'jsp',"personnels_id" : 1},
{"id" : 3,"skill_name": 'asp',"personnels_id" : 2}
]
};
我想合并两个json数组
(人员id =技能人员_id)
技能阵列进入人员阵列
喜欢这个结果:
{merge:[
{"id":1,"name":"bruce","sex:1,"skill":[{"id": 1,"skill_name": 'php', "personnels_id" : 1},{"id": 2,"skill_name": 'jsp',"personnels_id" : 1}]},
{"id":2,"name":"peter","sex":0,"skill":[{"id": 3,"skill_name": 'asp',"personnels_id" : 2}
]
};
我该怎么办,请帮帮我,谢谢。
答案 0 :(得分:2)
如果您在模型中正确配置了关系,则应该能够执行以下操作:
$personnel = Personnel::with('skills')->get();
return view('bs_sidebar/recommend', compact('personnel'));
修改强> 鉴于您的模型,如果您添加以下关系,您将能够使用上面的Eloquent查询。
class Personnel extends Model
{
protected $table = 'personnels';
protected $fillable = [
'name',
'sex',
];
public function skills()
{
return $this->hasMany(Personnels_skill::class, 'personnel_id', 'id');
}
}
class Personnels_skill extends Model
{
protected $table = 'personnels_skill';
protected $fillable = [
'personnel_id',
'skill_name',
];
public $timestamps = false;
public function personnel()
{
return $this->belongsTo(Personnel::class, 'id', 'personnel_id');
}
}
答案 1 :(得分:0)
让我们试试吧 它会工作。
foreach ($personnels as $key => $value) {
$skill_list = DB::table('skill')->where('personnels_id','=',$value->id)->get();
$personnels[$key]->skill = $skill_list;
}
return view('bs_sidebar/recommend',['personnels' => $personnels]);