2017-04-14 159 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