php - Create record with Relation Laravel 5.1 -
hi have next code create records
institution::create($request->all()); user::create([ 'name' => $request['name'], 'lastname' => $request['lastname'], 'phone' => $request['phone'], 'email' => $request['email'], 'password' => $request['password'], 'state' => 1, 'profile_id' => 1, 'institution_id' => institution::max('id'), ]);
the last attributes user thats correct implement so? last 3 user attributes , correct way? or there better
using institution::max('id')
creates race condition. since create()
static method of eloquent::model
returns newly-created model, can do:
$institution = institution::create($request->all()); user::create([ 'name' => $request['name'], 'lastname' => $request['lastname'], 'phone' => $request['phone'], 'email' => $request['email'], 'password' => $request['password'], 'state_id' => 1, 'profile_id' => 1, 'institution_id' => $institution->id, ]);
creating record known parent ids fine if goal minimize number of database queries , have ids of related models.
another way it, though triggers more update queries, use eloquent's built-in methods adding related models. example:
$institution = institution::create($request->all()); $state = state::find(1); $profile = profile::find(1); $user = new user([ 'name' => $request['name'], 'lastname' => $request['lastname'], 'phone' => $request['phone'], 'email' => $request['email'], 'password' => $request['password'] ]); $user->state()->associate($state); $user->profile()->associate($profile); $user->profile()->associate($institution); $user->save();
however, in situation, since related models not loaded, , know ids, there no need fetch them associate them user.
Comments
Post a Comment