[英]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.