Laravel同步与可选参数的关系 [英] Laravel sync Relation with optional parameters

查看:34
本文介绍了Laravel同步与可选参数的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用同步功能来同步belongsToMany关系:

I use the sync function for syncing a belongsToMany Relation:

$model->products()->sync($productIds);

在$ productIds数组中,带有一些ID的平面数组-像这样的东西:

In the $productIds array there is flat array with some Id's - something like this:

$productIds = [1,3,5,6];

我想要什么:数据透视表还具有其他列,例如"created_by"和"updated_by".

What I want: The pivot table has also additional columns like "created_by" and "updated_by".

但是如何在不进行foreach循环的情况下将这些字段添加到我的数组中呢?有没有更短的方法可以做到这一点?

But how can I add these fields to my array WITHOUT doing a foreach loop? Is there a shorter way to do this?

我需要一个像这样的数组:

I need an array like this:

$productIds = [1 => [
     'created_by' => 1,
     'updated_by' => 1
],3 => [
     'created_by' => 1,
     'updated_by' => 1
],5 => [
     'created_by' => 1,
     'updated_by' => 1
],6 => [
     'created_by' => 1,
     'updated_by' => 1
]];

是的,我知道我可以使用foreach并在遍历数组时添加列.但是我想做的更短..有没有办法做得更短(也许用laravel)?

Yes I know I can do it with foreach and add the columns while I loop through the array. But I want do it shorter.. is there a way to do it shorter (perhaps with laravel)?

推荐答案

应该足以将您在代码示例中在 $ productIds 中设置的内容传递给 sync().

It should be enough to pass what you have set in $productIds in your code example to sync().

此方法不仅适用于整数数组.您还可以传递一个数组,其中key是同步的ID,value是应该为给定ID设置的数据透视表属性的数组.

This method works not only with array of integers. You can also pass an array where key is the synced ID and value is the array of pivot attributes that should be set for given ID.

这应该可以解决问题:

$productIds = [
  1 => [
    'created_by' => 1,
    'updated_by' => 1
  ]
  //rest of array
];

$model->products()->sync($productIds);

只需确保已在关系定义中将这些字段定义为枢轴字段即可.

Just make sure you have defined those fields as pivot fields in your relation definition.

为了根据$ productIds中的ID列表生成此类表,您可以执行以下操作:

In order to generate such table based on a list of IDs in $productIds you can do the following:

$productIds = array_fill_keys($productIds, array(
  'created_by' => 1,
  'updated_by' => 1,
));

这篇关于Laravel同步与可选参数的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆