我正在使用基于帐户模型的 Laravel 构建多租户 API,我通过在所有租户模型上使用特征(AccountScoped)来确定请求阅读器“帐户”正在使用的租户,一切都在邮递员上工作,但是为什么要测试标题在特质上是不可访问的。
AccountScoped (特征)
trait AccountScoped
{
protected static function bootAccountScoped()
{
$account_id = request()->header('Account');
dd($account_id);
if (empty($account_id)) {
return;
}
static::creating(function (Model $model) use ($account_id) {
$model->account_id = $account_id;
});
static::addGlobalScope('byAccount', function (Builder $builder) use ($account_id) {
$builder->where('account_id', '=', $account_id);
});
}
}
测试方法:
public function testActionIndexInController()
{
$categories = Category::where('account_id',$this->account->id)->get()->toJSON();
$response = $this->actingAs($this->user, 'api')
->withHeader('Account',$this->account->id)
->get(route('categories.index'));
$response->assertStatus(200)->assertSee($categories);
}
* $this->user 是一个带有 Accounts 的 User 实例模型,$this->account 是一个与所选用户相关的 Account 实例
但是当我运行测试时,我在 $account_id 测试返回上得到空值
当我通过邮递员提出相同的请求时,值就在那里 邮递员返回