人気のPHP WEBアプリケーションフレームワークLaravelのTipsを記録していきます

Laravelで1対1のリレーションを複数回取得する

Laravelでテーブルが2つ「clients」「users」あって、「clients」テーブル内に登録者IDと更新者IDが格納されている場合に 更新者の名前を取得する方法。

● モデルに1対1 リレーションを設定

app/Client.php

DBカラムの

「clients.created_user_id」と「users.id」と同じデータがあれば取得します。
「clients.updated_user_id」と「users.id」と同じデータがあれば取得します。
    /**
     * 1対1リレーション
     *
     * @return \Illuminate\Database\Eloquent\Relations\hasOne
     */
    public function created_user()
    {
        return $this->hasOne('App\User', 'id', 'created_user_id')->withDefault();
    }


    /**
     * 1対1リレーション
     *
     * @return \Illuminate\Database\Eloquent\Relations\hasOne
     */
    public function updated_user()
    {
        return $this->hasOne('App\User', 'id', 'updated_user_id')->withDefault();
    }

->withDefault() がミソですね。存在しないときに中身が空のオブジェクトを返します。

● with メソッドの引数を複数指定する

$clients = Client::with('created_user','updated_user')->get();

● コントローラーから取得する時に with メソッドを2回投げる。

app/Http/Controllers/ClientController.php

	public function index( Request $request )
	{
		$clients = Client::with('created_user')
							->with('updated_user')
							->orderBy('id', 'desc')->paginate( 10 );
    }

引用: https://goo.gl/6h6LEC

No.1316
03/05 16:37

edit