2017-04-14 152 views
0

在我的应用程序中,我在测试过程中对复制表使用自定义类。这个班级使用_test后缀创建新表格,并告诉雄辩与他们合作。但是,当我使用“多对多”关系时,我需要指定数据透视表名称。运行时应用程序可以更改数据透视表吗?Laravel动态数据透视表

回答

0

如果我已经正确理解你的问题,那么你希望能够动态地改变你的表在多对多的关系。

请注意的belongsToMany关系源代码:

public function belongsToMany($related, $table = null, $foreignKey = null, $relatedKey = null, $relation = null) 
{ 
    // If no relationship name was passed, we will pull backtraces to get the 
    // name of the calling function. We will use that function name as the 
    // title of this relation since that is a great convention to apply. 
    if (is_null($relation)) { 
     $relation = $this->guessBelongsToManyRelation(); 
    } 

    // First, we'll need to determine the foreign key and "other key" for the 
    // relationship. Once we have determined the keys we'll make the query 
    // instances as well as the relationship instances we need for this. 
    $instance = $this->newRelatedInstance($related); 

    $foreignKey = $foreignKey ?: $this->getForeignKey(); 

    $relatedKey = $relatedKey ?: $instance->getForeignKey(); 

    // If no table name was provided, we can guess it by concatenating the two 
    // models using underscores in alphabetical order. The two model names 
    // are transformed to snake case from their default CamelCase also. 
    if (is_null($table)) { 
     $table = $this->joiningTable($related); 
    } 

    return new BelongsToMany(
     $instance->newQuery(), $this, $table, $foreignKey, $relatedKey, $relation 
    ); 
} 

可以定义表存在。因此,我建议你做如下:(考虑UserCompany模型之间的许多一对多的关系)

public function users(){ 
    $table = env('APP_ENV') == 'production' ? 'table_name' : 'test_table_name'; 
    $this->belongsToMany(User::class, $table); 
} 

和我从来没有测试这一点,但基本上它应该工作的公司模式 这样做。

+0

这是一个不好的解决方案。这意味着我需要修改我的应用程序中的每个belongsToMany关系。我需要这样的东西:$ model-> users() - > setTable('table_name_test') – Nitromoon