-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathsync_attach_examples.php
67 lines (53 loc) · 1.91 KB
/
sync_attach_examples.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?php
######### REGISTER A CHECKBOX ARRAY TO A PIVOT TABLE WITH EXTRA FIELDS:
# Table columns: id
#quality_id
#product_id
#buyer_id
#color <- extra field
#humidity <- extra field
// Code:
$arrayQualitiesIds = $request->get('qualitiesProductCheckbox');
//apilar en un array_map los valores de las llaves foraneas de la tabla pivot
//incluido el buyer_id, a pesar de que este tiene la relación 'qualities' no registro
//automaticamente el id del buyer si no que se tuvo que pasar en el array_map:
$extra = array_map(function($qualityId) use($request, $buyer){
return ['quality_id' => $qualityId,
'product_id' => $request->product,
'buyer_id' => $buyer->id,
'color' => $request->color,
'humidity' => $request->humidity];
}, $arrayQualitiesIds);
//combibar arreglos
$data = array_combine($arrayQualitiesIds, $extra);
$buyer->qualities()->sync($data); //sync -> update, write or delete
//or you can use attach:
$buyer->qualities()->attach($data); //attach you can append a lot of data without delete/update
// Example of sync for pivot table 2:
/*
- event_id
- participant_id
- state_payment (SI/NO)
*/
$extra = array(
'state_payment' => $request->state_payment
);
$participant->event()->sync([$request->event => $extra]);
########### REGISTER ARRAY USING ATTACH TO A PIVOT TABLE:
// Table pivot columns:
#id
#logistic_cost_id
#expense_type_id
#quantity <- extra field
#price <- extra field
$logisticCost = LogisticCost::findOrFail($logisticCostId);
// build array
$extra = array(
'expense_type_id' => $request->expenseType,
'quantity' => $request->quantity,
'price' => $request->price
);
//dd($extra);
//Registrar detalle en la tabla pivot 'expense_logistic' usando la relación:
$logisticCost->expenses()->attach($logisticCost->id, $extra);
?>