在Eloquent中使用具有数据透视表字段的访问器

eua*_*ano 15 laravel eloquent laravel-4

我现在有一些模型通过laravel有很多关系.这是结构:

users
    id
    username
    ...

games
    id
    title
    ...

game_user
    game_id
    user_id
    system
Run Code Online (Sandbox Code Playgroud)

现在,我的模型看起来有点像这样:

<?php

class Game extends Eloquent
{
    /**
     * A game is owned by many users
     *
     * @return mixed
     */
    public function user()
    {
        return $this->belongsToMany('User')->withPivot('system');
    }


<?php

class User extends Eloquent
{
    /**
     * A user has many games.
     *
     * @return mixed
     */
    public function games()
    {
        return $this->belongsToMany('Game')->withPivot('system');
    }
Run Code Online (Sandbox Code Playgroud)

现在,一切正常.但是,我希望在数据透视表的系统字段上使用mutator.我找不到任何关于此的文档,以下(在用户和游戏模型中)不起作用:

public function getSystemAttribute($val)
{
    return $val.' Testing';
}
Run Code Online (Sandbox Code Playgroud)

Col*_*mes 9

我没有测试,但这应该工作.

public function getSystemAttribute($value)
{
    return $this->pivot->system . ' Testing';
}

...

foreach ($user->games as $game)
{
    echo $game->system;
}
Run Code Online (Sandbox Code Playgroud)

传入的值是从模型属性中提取的.没有系统属性,所以你应该得到NULL.我们可以忽略它并直接从数据透视表中提取值.


clo*_*986 2

我发现这个问题很有趣,所以我开始研究代码。

如果您需要访问特定条目,这是我的解决方案:

public function getSystemAttribute($game){
    foreach($this->games as $value){
        if($value->id==$game->id){
            $value->pivot->system = 'foo';
            $value->pivot->save();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以简单地调用它:

$user->getSystemAttribute($game)
Run Code Online (Sandbox Code Playgroud)

关于访问器,如果不迭代集合,我找不到任何其他方法。有更漂亮的方法来迭代集合,但这不是这个问题的范围。从文档中,您可以看到如何访问数据透视表的任何属性。

希望这可以帮助