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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化