Bruce
Bruce

Reputation: 181

laravel ORM merge two json arrays

Excuse me, I use laravel ORM have two json arrays , like this:

php

$personnels = Personnel::all();
$skills = Languagelv::all();
return view('bs_sidebar/recommend',[
            'personnels' => $personnels,
            'skills' => $skills,
]);

model

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 result

{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}
       ]
};

I want to merge two json arrays

(personnels id = skill personnels_id )

skill arrays is into personnels arrays

like this result:

{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}
        ]
};

How can I do , please help me, thank you.

Upvotes: 0

Views: 855

Answers (2)

fubar
fubar

Reputation: 17398

If you have your relationships correctly configured in your models, you should be able to do the following:

$personnel = Personnel::with('skills')->get();
return view('bs_sidebar/recommend', compact('personnel'));

Edit Given your models, if you add the following relationships you will be able to use the Eloquent query above.

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');
    }
}

Upvotes: 3

Saravanan Nandhan
Saravanan Nandhan

Reputation: 612

let's try this it will work.

      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]);

Upvotes: 0

Related Questions