Laravel sync Relation with optional parameters

那年仲夏 提交于 2021-02-08 03:39:26

问题


I use the sync function for syncing a belongsToMany Relation:

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

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

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

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

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
]];

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)?


回答1:


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

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.

This should do the trick:

$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.

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,
));


来源:https://stackoverflow.com/questions/34180963/laravel-sync-relation-with-optional-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!