0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

リレーションを使ったデータの取得(個人用メモ)

0
Posted at

1.リレーションを使ってデータを取得したい場合は**with(リレーション)**を使用する。

$viewData = User::with(hoge)->get()~

2.レイレーションを複数使用したい場合は、配列にしてつなげる。

$viewData = User::with([hoge1,hoge2,hoge3])->get()~

3.ネストしたリレーションは「.」でつなぐ。

$viewData = User::with(hoge.fuga)->get()~

4.リレーションを繋げて特定のカラムだけ取得したい場合はリレーション:カラム名を指定する

$viewData = User::with(hoge:id,name)->get()~

最終コード(個人的なコードです)

public function hoge()
    {
        $viewData = User::with(['mstPrefecture:id,value', 'memberMainSkill:id,value', 'memberSubSkills', 'memberOtherSkills.memberOtherImages:id,image_path', 'memberImages', 'joinWorks'])->get()->map(function ($member){
            return [
                'id'            => $member->id,
                'name'          => $member->name,
                'email'         => $member->email,
                'prefecture'    => $member->mstPrefecture,
                'mainSkill'     => $member->memberMainSkill,
                'joinedAt'      => $member->joined_at,
                'firstWorkedAt' => $member->first_worked_at,
                'subSkills'     => $member->memberSubSkills->map(function($subskill){
                    return [
                        'id'    => $subskill->id,
                        'value' => $subskill->value,
                    ];
                }),
                'otherSkills'   => $member->memberOtherSkills->map(function ($otherSkill){
                    return [
                        'id'           => $otherSkill->id,
                        'name'         => $otherSkill->name,
                        'description'  => $otherSkill->description,
                        'image'        => $otherSkill->memberOtherImages,
                    ];
                }),
                'images'        => $member->memberImages->map(function ($image){
                    return [
                        'id'   => $image->id,
                        'path' => $image->image_path,
                    ];
                }),
                'workCount'     => $member->joinWorks->count(),
            ];
        });
        
        return response()->json($viewData);
    }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?