LoginSignup
23
12

More than 5 years have passed since last update.

Laravelを勉強していて学んだことを書いていく 20181022

Posted at

has one結合

2つのテーブルを「1対1」の関係で関連づけられることをいう。

Person.phpに下記を追記する。

Person.php
public function board()
{
    return $this->hasOne('App\Board');
}

関連テーブルの情報を表示するようにテンプレートを修正する。
Person/index.blade.phpを修正する。

index.blade.php
@section('content')
    <table>
        <tr><th>Person</th><th>Board</th></tr>
        @foreach ($items as $item)
            <tr>
                <td>{{$item->getData()}}</td>
                <td>
                    @if ($item->board != null)
                        {{$item->board->getData()}}
                    @endif
                </td>
            </tr>
        @endforeach
    </table>
@endsection

上記を修正すると下図のようにboardsテーブルと紐づいて表示される。

スクリーンショット 2018-10-21 22.02.08.png

has Many結合

Personモデルのboardメソッドを修正する。

Person.php
public function boards()
{
    return $this->hasMany('App\Board');
}

/Person/index.blade.phpを修正する。

oinde.blade.php
@section('content')
    <table>
        <tr><th>Person</th><th>Board</th></tr>
        @foreach ($items as $item)
            <tr>
                <td>{{$item->getData()}}</td>
                <td>
                    @if ($item->boards != null)
                        <table width="100%">
                            @foreach ($item->boards as $obj)
                                <tr><td>{{$obj->getData()}}</td></tr>
                            @endforeach
                        </table>
                    @endif
                </td>
            </tr>
        @endforeach
    </table>
@endsection

修正すると下図のように全ての利用者の投稿が表示される。

スクリーンショット 2018-10-22 7.29.02.png

belongsTo結合

belongsToとは、従テーブル(boards)から、関連づいている主テーブル(people)のレコードを取り出すこと。

Boardモデルクラスを修正する。

Board.php
public function person()
{
    return $this->belongsTo('App\Person');
}

public function getData()
{
    return $this->id . ': ' . $this->title . ' (' . $this->person->name . ')';
}

しかしこのコードを書いても/boardにアクセスするとエラーが発生してしまう。
Trying to get property of non-objectということはプロパティのオブジェクトを取得できないらしい。

Laravel belongsToでリレーションした主テーブルのプロパティが取得できない

この記事によると personからの値を取得するには連想配列にするとうまくいくみたい。

Board.php

public function getData()
{
    return $this->id . ': ' . $this->title . ' (' . $this->person['name'] . ')';
}

出力確認したらこれでOKそう。苦労した。

スクリーンショット 2018-10-23 0.14.54.png

23
12
2

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
23
12