douhan1860 2018-07-24 19:21
浏览 93
已采纳

Laravel使用firstOrCreate同步多个

I used to select my tags in a multiple dropdown, but I changed it to a text field where I can manually input multiple tags. I then simply call a firstOrCreate method and I then want to sync() them to my model, but I cannot figure out how to do that. My code so far:

// Here I simply create my new model
$expense = auth()->user()->expenses()->create($request->all());

$tags = [];

// For each entered tag I grab it from the database or I create it
foreach(explode(",", $request->tags) as $tag)
{
    $tags[] = auth()->user()->tags()->firstOrCreate(['name' => $tag]);
}

// Here is what I used to do, but I had an array of tag_ids
$expense->tags()->sync($tags);

Unsure what to do next, also my first time using firstOrCreate, so any pointer on how to improve the above code perhaps would be also very welcome. But ofcourse my main question is, how to sync the tag objects to my newly created expense?

  • 写回答

1条回答 默认 最新

  • douju5933 2018-07-24 19:37
    关注

    It was actually quite simple, just have to add the ->value('id'):

    $tags[] = auth()->user()->tags()->firstOrCreate(['name' => $tag])->value('id');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘