duanji9481 2017-07-25 08:49
浏览 67
已采纳

Laravel mutator或创建活动

I have two models, Card and Expense. Both have a type field. Whenever I add a new expense, I have a dropdown in the form to select a Card. They are related by a belongsTo relation.

The thing is, I want to automatically set the type field of my Expense to the same as my card's type. I do not want to have another dropdown for type in my expense form. Also, I want to keep using the following on my store method on my Expense Controller:

auth()->user()->expenses()->create($request->all());

I think this should be possible by using a mutator perhaps in the model, but I'm not entirely sure how to approach this.

So in short, what I need is, when creating a new Expense, I need the type field to be grabbed from the related Card, and then inserted into the Expense type field.

What I don't want to do in my controller, is something like:

$expense = new Expense;
$expense->name = ... And so on
  • 写回答

1条回答 默认 最新

  • duandanxiu6965 2017-07-25 08:54
    关注

    If you want to use type from the Card model, you could do something like this:

    $card = Card::find(1);
    $card->expenses()->create(array_merge($request->all(), ['type' => $card->type]));
    

    But it's not a good idea to duplicate type if you already have one in the Card model and Expense belongs to Card.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog