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

报告相同问题?

悬赏问题

  • ¥50 高维数据处理方法求指导
  • ¥100 数字取证课程 关于FAT文件系统的操作
  • ¥15 如何使用js实现打印时每页设置统一的标题
  • ¥15 安装TIA PortalV15.1报错
  • ¥15 能把水桶搬到饮水机的机械设计
  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器
  • ¥15 关于#爬虫#的问题:请问HMDB代谢物爬虫的那个工具可以提供一下吗
  • ¥15 vue3+electron打包获取本地视频属性,文件夹里面有ffprobe.exe 文件还会报错这是什么原因呢?
  • ¥20 用51单片机控制急停。