Help us understand the problem. What is going on with this article?

Laravelのリレーション hasManyThrough の使い方を毎回間違うのでメモ

More than 1 year has passed since last update.

目的

特定のユーザーの所持するゲーム一覧をリレーションテーブルを経由してマスタを取得したい。

ユーザーテーブル

user_master_id name
1 田中太郎
2 岡たけし
3 Niclas Karlsson

ゲームマスタテーブル

game_master_id name
1 ファイナルファイト
2 聖剣伝説2
3 桃太郎伝説

ユーザーごとの所持ゲームテーブル

id user_id game_id
1 1 1
2 1 3
3 2 1
4 2 2
5 3 2

ユーザーをベースにしたモデル

// ユーザーモデル
class User extends Model
{
    public function Games() {
        return $this->hasManyThrough(, , , , , ); // ← 毎回忘れる
    }
}

答え

番号 user_id
リレーションを経由したあとに取得したいモデル (Model\Game)
リレーション用のモデル (Model\UserGame)
②のモデルを呼び出し元のモデル (Model\User) と結びつけるために使うキー (user_id)
①のマスタID (game_master_id)
不明
②のモデルを①のモデルと結びつけるために使うキー (game_id)

つまり

return $this->hasManyThrough(
    Model\Game::class,
    Model\UserGame::class,
    'user_id',
    'game_master_id',
    null,
    'game_id'
);
YuK1Game
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした