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