doushang1890
2017-10-14 22:59
浏览 63
已采纳

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?

图片转代码服务由CSDN问答提供 功能建议

我正在尝试在Laravel中编写一个测试用例。 我发现这里如何为多对多之间的关系创建虚拟数据 两种型号。 但我找不到如何向数据透视表添加属性。

这是一个例子: 我们有一个模型 user 和一个模型 car 。 每个用户可以驾驶多辆汽车,每辆汽车可以由多个用户驾驶,我们希望捕获每个用户驾驶每辆汽车的里程数。

users table

  id | 名字
 1 | 鲍勃
 2 |  Alice 
   
 
 

cars table

  id | 名字
 1 | 红车
 2 |  Blue Car 
   
 
 

car2user relation table

  id_user |  id_car | 英里
 1 |  1 |  20 
 2 |  2 |  4 
   
 
 

如何创建这样的测试用例? 我试过

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

但这会引发错误:

一般错误:1364字段“里程”不 有一个默认值

我接受此错误消息,因为我没有指定必填字段 miles 的值。 但是我可以在哪里提供这个价值?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douxin0251 2017-10-15 03:04
    已采纳

    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]);
    
    点赞 评论

相关推荐 更多相似问题