3

私は自分が抱えている論理的な問題を解き明かそうとしていますが、他にどこに質問すればよいかわかりません!

私は関係を説明しようとしている 2 つのオブジェクトを持っています。UserGame。_ それで、今、私は aが many にUser属し、 a が manyGamesに属していることをGame知っていUsersます。私が説明しようとしているのは、 aが aUserを所有している場合の特別なインスタンスGameです。おそらく、これは単に のテーブル内の列になりますowner_id。しかし、これを Eloquent で表現する方法を確立するのに苦労しています。ゲーム所有者のために新しいオブジェクトを作成する必要がありますか? または、ある種のユーザー ロールを使用してこれを説明できますか?

ゲーム

class Game extends Eloquent 
{
    protected $guarded = array();
    public static $rules = array();

    // Game belongsToMany User
    public function users()
    {
        return $this->belongsToMany('User');
    }

    // Need to identify the owner user.
}

ユーザー

class User extends Eloquent
{
    protected $guarded = array();
    public static $rules = array();

    // User belongsToMany Game
    public function games()
    {
        return $this->belongsToMany('Game');
    }
}

これを明確かつ簡潔に尋ねる方法を理解することさえ難しいので、さらに詳細が必要な場合は、遠慮なく尋ねてください.

4

1 に答える 1

2

必要なのはこのテーブルです: games_owners. これはそのための移行スキーマです:

Schema::create('games_owners', function($table)
{
    $table->increments('id');
    $table->integer('user_id');
    $table->integer('game_id');
    $table->timestamps();
});

これは User モデルになります。

class User extends Eloquent
{
    protected $guarded = array();
    public static $rules = array();

    // User belongsToMany Game
    public function games()
    {
        return $this->belongsToMany('Game', 'games_owners', 'user_id');
    }
}

そしてあなたのゲームモデル:

class Game extends Eloquent 
{
    protected $guarded = array();
    public static $rules = array();

    // Game belongsToMany User
    public function users()
    {
        return $this->belongsToMany('User', 'games_owners', 'game_id');
    }

    // Need to identify the owner user.
}

そして、次のようなことができるようになります:

$user = User::find(1);

foreach($user->games as $game) {
    echo $game->name;
}
于 2013-12-23T21:19:32.107 に答える