参考図書
前提
PersonモデルとBoardモデルがリレーションしている。
Personモデルには人のレコードが、Boardモデルには掲示板へのコメントがレコードされている。
Boardモデルは投稿者のレコードとなるPersonモデルに必ず関連付けられている。
しかし、Personモデルはそうではない。頻繁に投稿すれば、東欧しない人もあいる。Personモデルは関連するBoardを複数持つ場合もあれば、まったく持たない場合もある。
このような場合、関連するBoardを持っているPerson、または、関連するBoardを持たないPersonを取り出さればいろいろ役に立ちそう。
特定のリレーションを持つ
モデル::has(リレーション名)->get();
特定のリレーションを持たない
モデル::doesntHave(リレーション名)->get();
実例
値の取得
app/Http/Controllers/PersonController.php
public function index(Request $request){
$hasItems = Person::has('boards')->get();
$noItems = Person::doesntHave('boards')->get();
$param = ['hasItems' => $hasItems, 'noItems' => $noteItems];
return view('person.index', $param);
}
値の表示
resources/views/Person/index.blade.php
@section('content')
<table>
    <tr><th>Person</th><th>Board</th></tr>
    @foreach ($hasItems as $item)
        <tr>
            <td>{{$item->getData()}}</td>
            <td>
                <table width="100%">
                @foreach ($item->boards as $obj)
                    <tr><td>{{$obj->getData()}}</td></tr>
                @endforeach
                </table>
            </td>
        </tr>
    @endforeach
</table>
<div style="margin:10px;"></div>
<table>
    <tr><th>Person</th></tr>
    @foreach ($noItems as $item)
        <tr>
            <td>{{$item->getData()}}</td>
        </tr>
    @endforeach
</table>
@endsection