如何关联belongsToMany关系中的数据透视字段

时间:2015-07-15 12:44:41

标签: php laravel eloquent laravel-5

其实我有这种情况:

  • 1个用户属于许多客户
  • 在此关系中 - public class BoundingRectangle extends Application { @Override public void start(Stage primaryStage) { Pane pane = new Pane(); ArrayList<Circle> list = new ArrayList<>(); Rectangle rectangle1 = new Rectangle(10, 10, 175, 80); rectangle1.setStroke(Color.BLACK); rectangle1.setFill(Color.WHITE); Rectangle rectangle2 = new Rectangle(250, 75, 300, 200); rectangle2.setStroke(Color.BLACK); rectangle2.setFill(Color.WHITE); Text text = new Text(20, 33, "INSTRUCTION\n" + "Add: Left Click\nRemove: Right Click"); pane.setOnMouseClicked(e -> { if (e.getButton() == MouseButton.PRIMARY) { Circle circle = new Circle(e.getX(), e.getY(), 10); list.add(circle); circle.setStroke(Color.BLACK); circle.setFill(Color.WHITE); if (circle.getCenterX() - rectangle2.getX() < 10) { circle.setCenterX(rectangle2.getX() + 10); } else if (circle.getCenterY() - rectangle2.getY() < 10) { circle.setCenterY(rectangle2.getY() + 10); } else if (rectangle2.getX() + rectangle2.getWidth() - circle.getCenterX() < 10) { circle.setCenterX(rectangle2.getX() + rectangle2.getWidth() - 10); } else if (rectangle2.getY() + rectangle2.getHeight() - circle.getCenterY() < 10) { circle.setCenterY(rectangle2.getY() + rectangle2.getHeight() - 10); } pane.getChildren().add(circle); } else if (e.getButton() == MouseButton.SECONDARY) { for (int i = 0; i < list.size(); i++) { if (list.get(i).contains(e.getX(), e.getY())) { pane.getChildren().remove(list.get(i)); list.remove(i); break; } } } }); pane.getChildren().addAll(rectangle1, rectangle2, text); Scene scene = new Scene(pane, 600, 300); primaryStage.setScene(scene); primaryStage.setTitle("BoundingRectangle"); primaryStage.show(); } } - 我需要保存customers_users即创建此关系的
created_user_id

如何在我的Eloquent模型中关联这个额外字段?我需要像这样访问这些信息:

public function customers()
{
    return $this->belongsToMany('Project\DB\Customer', 'customers_users')
        ->withPivot('created_user_id');
}

我使其成功的唯一方法是制作手动加入,但我想用雄辩的方式做到这一点。

如果您需要更多信息,请告诉我。

1 个答案:

答案 0 :(得分:-1)

如果客户尚未保存

$user->customers()->save($customer, ['created_user_id' => $creatorUser->id]);

如果custemer已经保存

$user->customers()->attach($customer->id, ['created_user_id' => $creatorUser->id]);