[英]Laravel dynamic pivot table
在我的應用程序中,我在測試過程中使用自定義類復制表。 此類使用_test
后綴創建新表,並告訴雄辯者使用它們。 但是,當我使用“多對多”關系時,我也需要指定數據透視表名稱。 在運行時應用程序期間可以更改數據透視表嗎?
如果我正確理解了您的問題,那么您希望能夠動態更改多對多關系中的表。
請注意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);
}
並針對公司模型執行相同的操作,我從未對此進行過測試,但基本上應該可以工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.