0
私のアプリでは、テスト中にレプリケートテーブルのカスタムクラスを使用します。このクラスは、_test
の接尾辞を持つ新しい表を作成し、それらの表記を操作するために雄弁に伝えます。しかし、私が "多対多"の関係で作業するとき、ピボットテーブル名も指定する必要があります。ランタイムアプリケーションの実行中にピボットテーブルを変更することは可能ですか?Laravel動的ピボットテーブル
私のアプリでは、テスト中にレプリケートテーブルのカスタムクラスを使用します。このクラスは、_test
の接尾辞を持つ新しい表を作成し、それらの表記を操作するために雄弁に伝えます。しかし、私が "多対多"の関係で作業するとき、ピボットテーブル名も指定する必要があります。ランタイムアプリケーションの実行中にピボットテーブルを変更することは可能ですか?Laravel動的ピボットテーブル
質問を正しく理解していれば、多対多の関係でテーブルを動的に変更できます。
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
);
}
あなたがそこにテーブルを定義することができます。私はこれをテストしたことはありませんが、基本的にはそれが動作するはずです(User
とCompany
モデル間の多対多の関係を考える)
public function users(){
$table = env('APP_ENV') == 'production' ? 'table_name' : 'test_table_name';
$this->belongsToMany(User::class, $table);
}
と当社モデル のために同じ操作を行います。だから私は、あなたが以下のように行うことをお勧めします。
これは悪い解決策です。つまり、私は自分のアプリケーション内の各belongsToMany関係を変更する必要があることを意味します。私はそのようなものが必要です:$ model-> users() - > setTable( 'table_name_test') – Nitromoon