php Laravel,sync() - 如何同步数组并传递额外的枢轴字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27230672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel, sync() - how to sync an array and also pass additional pivot fields?
提问by Томица Кора?
Official Laravel documentation has this on sync()
function:
官方 Laravel 文档有这个sync()
功能:
$user->roles()->sync( array( 1, 2, 3 ) );
You may also associate other pivot table values with the given IDs:
您还可以将其他数据透视表值与给定的 ID 相关联:
$user->roles()->sync( array( 1 => array( 'expires' => true ) ) );
In the latter example only a single pivot row is being added. What I don't understand is how can I associate other pivot table records if there are more than one rows to be synced?
在后一个示例中,仅添加了一个枢轴行。我不明白的是,如果要同步的行不止一行,我如何关联其他数据透视表记录?
Thanks in advance.
提前致谢。
回答by Jarek Tkaczyk
In order to sync
multiple models along with custom pivot data, you need this:
为了sync
多个模型以及自定义数据透视数据,您需要:
$user->roles()->sync( array(
1 => array( 'expires' => true ),
2 => array( 'expires' => false ),
...
));
Ie.
IE。
sync( array(
related_id => array( 'pivot_field' => value ),
...
));
edit
编辑
Answering the comment:
回复评论:
$speakers = (array) Input::get('speakers'); // related ids
$pivotData = array_fill(0, count($speakers), ['is_speaker' => true]);
$syncData = array_combine($speakers, $pivotData);
$user->roles()->sync($syncData);
回答by The Dude
This works for me
这对我有用
foreach ($photos_array as $photo) {
//collect all inserted record IDs
$photo_id_array[$photo->id] = ['type' => 'Offence'];
}
//Insert into offence_photo table
$offence->photos()->sync($photo_id_array, false);//dont delete old entries = false
回答by Miguel Trevino
Attaching / Detaching
安装/拆卸
Eloquent also provides a few additional helper methods to make working with related models more convenient. For example, let's imagine a user can have many roles and a role can have many users. To attach a role to a user by inserting a record in the intermediate table that joins the models, use the attach method:
Eloquent 还提供了一些额外的辅助方法,使使用相关模型更加方便。例如,假设一个用户可以有多个角色,一个角色可以有多个用户。要通过在连接模型的中间表中插入记录来将角色附加到用户,请使用 attach 方法:
$user = App\User::find(1);
$user->roles()->attach($roleId);
When attaching a relationship to a model, you may also pass an array of additional data to be inserted into the intermediate table:
将关系附加到模型时,您还可以传递要插入中间表的附加数据数组:
$user->roles()->attach($roleId, ['expires' => $expires]);
You can also use Sync if you want to remove old roles and only keep the new ones you are attaching now
如果您想删除旧角色并仅保留您现在附加的新角色,也可以使用同步
$user->roles()->sync([1 => ['expires' => $expires], 2 => ['expires' => $expires]);
The default behaviour can be changed by passing a 'false' as a second argument. This will attach the roles with ids 1,2,3 without affecting the existing roles.
可以通过将“false”作为第二个参数传递来更改默认行为。这将附加 ID 为 1、2、3 的角色,而不会影响现有角色。
In this mode sync behaves similar to the attach method.
在这种模式下,sync 的行为类似于 attach 方法。
$user->roles()->sync([1 => ['expires' => $expires], 2 => ['expires' => $expires], false);
Reference: https://laravel.com/docs/5.4/eloquent-relationships
回答by Tom van Tilburg
Add following trait to your project and append it to your model class as a trait. This is helpful, because this adds functionality to use multiple pivots. Probably someone can clean this up a little and improve on it ;)
将以下特征添加到您的项目中,并将其作为特征附加到您的模型类中。这很有帮助,因为这增加了使用多个枢轴的功能。可能有人可以稍微清理一下并改进它;)
namespace App\Traits;
trait AppTraits
{
/**
* Create pivot array from given values
*
* @param array $entities
* @param array $pivots
* @return array combined $pivots
*/
public function combinePivot($entities, $pivots = [])
{
// Set array
$pivotArray = [];
// Loop through all pivot attributes
foreach ($pivots as $pivot => $value) {
// Combine them to pivot array
$pivotArray += [$pivot => $value];
}
// Get the total of arrays we need to fill
$total = count($entities);
// Make filler array
$filler = array_fill(0, $total, $pivotArray);
// Combine and return filler pivot array with data
return array_combine($entities, $filler);
}
}
Model:
模型:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Example extends Model
{
use Traits\AppTraits;
// ...
}
Usage:
用法:
// Get id's
$entities = [1, 2, 3];
// Create pivots
$pivots = [
'price' => 634,
'name' => 'Example name',
];
// Combine the ids and pivots
$combination = $model->combinePivot($entities, $pivots);
// Sync the combination with the related model / pivot
$model->relation()->sync($combination);
回答by X 47 48 - IR
Simply just appendyour fieldsand their valuesto the elements:
只需将您的字段及其值附加到元素:
$user->roles()->sync([
1 => ['F1' => 'F1 Updated']
]);
回答by Deivid Criollo
$data = array();
foreach ($request->planes as $plan) {
$data_plan = array($plan => array('dia' => $request->dia[$plan] ) );
array_push($data,$data_plan);
}
$user->planes()->sync($data);