0
0

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 1 year has passed since last update.

【Laravel】外部キーがデフォルトでないリレーションの定義

Posted at

環境

Laravel v9.5.1 (PHP v8.1.3)

外部キーがデフォルトでないリレーション定義

通常はEloquentGiftHistoryモデルにuser_idカラムがあると想定するが、
今回のように外部キーがデフォルトと違う場合は、belongsToメソッドの2番目の引数としてカスタムキー名を渡す。

app/Models/GiftHistory.php
public function giver(): BelongsTo
{
	return $this->belongsTo(User::class, 'giver_id');
}

public function receiver(): BelongsTo
{
	return $this->belongsTo(User::class, 'receiver_id');
}

コンソールで実行するとリレーションで取得できるようになる。

GiftHistory::first()->giver()
=> Illuminate\Database\Eloquent\Relations\BelongsTo

GiftHistory::first()->receiver()
=> Illuminate\Database\Eloquent\Relations\BelongsTo

参考

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?