Laravelでテーブルが2つ「clients」「users」あって、「clients」テーブル内に登録者IDと更新者IDが格納されている場合に 更新者の名前を取得する方法。
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() がミソですね。存在しないときに中身が空のオブジェクトを返します。
$clients = Client::with('created_user','updated_user')->get();
app/Http/Controllers/ClientController.php
public function index( Request $request )
{
$clients = Client::with('created_user')
->with('updated_user')
->orderBy('id', 'desc')->paginate( 10 );
}