Laravel测试:向数据透视表添加属性

I am trying to write a test case in Laravel. I have found here how to create dummy data for a many to many relation between two models. But I could not find how to add attributes to the pivot table.

Here an example: We have a model user and a model car. Each user can drive multiple cars, each car can be driven by multiple users and we want to capture how much miles each user drove with each car.

users table

 id | name
  1 | Bob
  2 | Alice

cars table

 id | name
  1 | Red Car
  2 | Blue Car

car2user relation table

 id_user | id_car | miles
  1      | 1      |  20
  2      | 2      |   4

How can I create such a test case? I tried

$user = factory(\App\User::class)->create(['name' => 'Bob'])->first();

$user->cars()->save(factory(\App\Car::class)->create(['name' => 'Red Car']));

But this raises the error:

General error: 1364 Field 'miles' doesn't have a default value

I accept this error message, because I did not specify anywhere the value for the mandatory field miles. But where can I provide that value?

You can pass extra pivot attributes as second argument to save() method. The following should do the trick:

$user->cars()->save(factory(\App\Car::class)->create(['name' => 'Red Car']), ['miles' => 20]);