价值观格式不同的雄辩关系

时间:2017-04-09 07:05:35

标签: php laravel eloquent laravel-5.2

我们最近切换到了正在处理的项目的新权限系统。

当集成的要求发生了一些变化时,我已经完成了对此的集成,雄辩的关系以及所有这些。

权限系统与我们基础架构中的所有系统集成,当涉及从Laravel项目引用用户时,权限系统中的值略有不同;因为它以user-为前缀。

例如,我的james表中具有用户名users的用户在权限系统表中被引用为user-james

有没有办法指定雄辩关系应该看的价值?

我可以在users表中添加一列来存储该用户的主键,因为它存在于权限表中,但是我想知道是否有办法用eloquent来执行此操作。

1 个答案:

答案 0 :(得分:1)

如果我们认为关系是一对一的,我们可以做如下的事情:

首先扩展BelongsTo关系并更改where子句的条件:

class CustomBelongsTo extends BelongsTo
{
    /**
     * @inheritDoc
     */
    public function addConstraints()
    {
        if (static::$constraints) {
            // For belongs to relationships, which are essentially the inverse of has one
            // or has many relationships, we need to actually query on the primary key
            // of the related models matching on the foreign key that's on a parent.
            $table = $this->related->getTable();

            $this->query->where($table.'.'.$this->otherKey, '=', 'user-'.$this->parent->{$this->foreignKey});
        }
    }

}

然后在模型上覆盖belongsTo方法以使用此自定义关系。

class User extends Model {

    protected $table = 'users';

    public function permissions(){
        return $this->belongsTo(Permission:class, 'username');
    }

    public function belongsTo($related, $foreignKey = null, $otherKey = null, $relation = null)
    {
        // If no relation name was given, we will use this debug backtrace to extract
        // the calling method's name and use that as the relationship name as most
        // of the time this will be what we desire to use for the relationships.
        if (is_null($relation)) {
            list($current, $caller) = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);

            $relation = $caller['function'];
        }

        // If no foreign key was supplied, we can use a backtrace to guess the proper
        // foreign key name by using the name of the relationship function, which
        // when combined with an "_id" should conventionally match the columns.
        if (is_null($foreignKey)) {
            $foreignKey = Str::snake($relation).'_id';
        }

        $instance = new $related;

        // Once we have the foreign key names, we'll just create a new Eloquent query
        // for the related models and returns the relationship instance which will
        // actually be responsible for retrieving and hydrating every relations.
        $query = $instance->newQuery();

        $otherKey = $otherKey ?: $instance->getKeyName();

        return new CustomBelongsTo($query, $this, $foreignKey, $otherKey, $relation);
    }
}

我希望这有帮助。