php - 我如何在 Laravel 的 Eloquent 中表示这种游戏所有者关系

标签 php laravel laravel-4 eloquent object-relational-model

我正试图梳理出我遇到的一个逻辑问题,但我不知道还能去哪里问!

我有两个对象,我试图描述它们之间的关系; 用户游戏。所以,现在,我有一个 User 属于许多 Games,一个 Game 属于许多 User。我要描述的是 User 拥有 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');
    }
}

我什至不知道如何以清晰简洁的方式提出这个问题,所以如果需要更多细节,请不要犹豫,尽管提出。

最佳答案

您需要的是这个表:games_owners。这是它的迁移模式:

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

这将是您的用户模型:

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;
}

关于php - 我如何在 Laravel 的 Eloquent 中表示这种游戏所有者关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20751222/

相关文章:

php - 将策略模式与环境变量 Laravel 一起使用

php - Laravel 路线仅接受特定格式

laravel - 如何在 TwigBridge 中访问 Laravel 4 错误?

javascript - 在一定时间后更改自定义字段

PHP爆炸并放入数组

php - 为什么 mix-manifest.json 不刷新?

php - Laravel 使用自定义验证消息

mysql - 无论如何分配一个表的默认值等于 id 本身?

php - Laravel db 迁移 - renameColumn 错误 - 请求了未知的数据库类型枚举

php - 从 Android 应用程序上传多个图像到服务器