親 :usersテーブル(->hasMany)、 子: pictures のリレーションにおいて、
子 picturesの 「user_id」 「review_user_id」 から、belongsToで親テーブルのユーザーを呼び込みたい時のモデルの書き方
### 子テーブルのmigration file
Schema::create('pictures', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id')->index()->unsigned();
// 省略
$table->integer('review_user_id')->index()->unsigned()->nullable();
$table->timestamps();
$table->softDeletes();
});
### 子テーブルのモデル
Picture.php
belongsToの第二引数に小テーブルのカラム、第三引数に親テーブルのカラムを記述する。
public function user(){
return $this->belongsTo('App\User');
}
public function reviewUser(){
return $this->belongsTo('App\User', 'review_user_id', 'id');
}
### 挙動テスト
Route::get('/read', function(){
// $user = Picture::findOrFail(1)->user;
// dd($user);
$user = Picture::findOrFail(2)->reviewUser;
return $user->name;
});
直ぐに解決するかと思いきや、ドキュメントが少なく意外と苦戦しました。こういうケースでは、Laravel側としては、usersテーブルから2回呼び込むのではなく、users, review_usersという風に親テーブルを分けて設計して欲しいのかもしれません。