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

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?

  • 写回答

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]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献