php - How to save a model with related records in Eloquent ORM from JSON -
the goal
an eloquent model, alum
, has many-to-many relationship school
. 1 alum can have gone many schools, , 1 school can have many alums.
using eloquent, can retrieve , output alum schools this:
$alums = alum::with('schools')->get(); echo $alums->tojson();
angularjs shows alums in table. each row has edit button shows dialog checkboxes schools alum have gone to. checking box adds school alum's schools
array, , unchecking box removes it.
so far good.
the problemposting or putting info server things go wrong. json that's sent server looks this:
{ "id":1, "name":"john doe", "schools": [ { "id":1, "name":"school a" }, { "id":2, "name":"school b" } ] }
the alum
record saves, eloquent doesn't know array of schools.
from laravel's documentation on inserting related models in eloquent, looks way save related records utilize attach
. attach
takes array of ids, not objects, seek following:
// ids of schools user attended $schoolids = []; foreach ($obj->schools $school) { $schoolids[] = $school->id; } $alum->schools()->attach($schoolids); $alum->save();
that works; alum , schools saved database. there's new problem: how detach schools when they're unchecked alum's school list. suppose ids of schools, splice out ones in array of checked schools, , pass result detach
—but hope there's more elegant way that.
what's best way save record , related records json?
funny how posting seems lead straight finding solution on own. had missed sync
in eloquent docs:
the sync method accepts array of ids place on pivot table. after operation complete, ids in array on intermediate table model[.]
after replacing attach
sync, checked schools saved in alum's school list.
i'm still curious if there's improve way save related records straight json, though. more input welcomed.
php mysql json angularjs eloquent
No comments:
Post a Comment