1
1

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 5 years have passed since last update.

hasManyThroughを使わずに、〜経由で多数へ紐づくモデルをCollectionで取得

Posted at

タイトルが微妙。。。

ひと言でどう表現したものか分からず、伝わりにくいかと思いますが。
忘備録としておいておきます。

やりたいこと

companyのidをもとにpassengersをcollectionで取得したい。
航空会社(company)は多数のフライト(flights)を持ち、各フライトは多数の乗客(passengers)をもつ。

companies
    id - integer
    name - string

flights
    id - integer
    company_id - integer
    destination - string

passengers
    id - integer
    flight_id - integer
    name - string

hasManyThrough使うといいんですが、今回は使わずにやりたい。
モデル同士はhasManyとbelongsToで定義されているものとします。

PassengerController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Company;

class PassengerController extends Controller
{
    public function getPasserngers($id)
    {
        $company = Company::find($id);
        // $companyに関連するflightsを取得
        $flights = Flight::where('company_id', $company->id)->get();
        // コレクションのインスタンスをつくる
        $passengers = new Collection;
        // foreachで回しながら、各flightに紐づくpassengersをcollectionで取得
        foreach ($flights as $flight) {
            $data = $flight->passengers;
            $passengers = collect($passengers)->merge($data);
        }
        // ついでにソートしておく
        $passengers = $passengers->sortByDesc('created_at');
        dd($passengers);  // collectionで取得できる
    }

ちなみに。

ちなみにhasManyThrough使うとすればこういう書き方かと思います。かんたん。。。

Company.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Company extends Model
{
    /**
     * ある会社の全乗客を取得
     */
    public function passengers()
    {
        //第一引数=最終的にアクセスするモデル、第二引数=仲介するモデル
        return $this->hasManyThrough('App\Passenger', 'App\Flight');
    }
}

PassengerController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Company;

class PassengerController extends Controller
{
    public function getPassengers($id)
    {
        $company = Company::find($id);
        $passengers = $company->passengers;
        // companyにひもづく全てのpassengersがcollectionで取得できる
        dd($passengers);
    }

}
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?