Search code examples
mysqltransactionseloquentmany-to-manylumen

New record and many to many insert


I am working in a project where the users have a rate plan associated. When a new user is created, a valid rate plan must be specified.

I have the following MySQL schema and Eloquent models:

enter image description here

/**
 * User Eloquent model file ...
 *
 */

public function ratePlans() {
    return $this->belongsToMany(
      'App\Models\RatePlan',
      'users_rate_plans',
      'users_id', 
      'rate_plans_id'
   );
}

So, to create a new user with your selected rate plan i do:

try {
   \DB::beginTransaction();
   $model->create($data);
   $model->ratePlans()->attach($data['rate_plan'], ['active' => 1]);
   \DB::commit();
   return $model;
} catch(\Exception $e) {
   \DB::rollback();
   return false;
}

But, i am getting the next exception:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'users_id' cannot be null (SQL: insert into users_rate_plans (active, rate_plans_id, users_id) values (1, 43, ))

Why te transaction didn't work ? How i can do that task ?

UPDATE 1

I changed the transaction code but, the result is the same.

try {
   \DB::beginTransaction();
   $ratePlan = \App\Models\RatePlan::find($data['rate_plan']);
   $user->ratePlans()->attach($ratePlan, ['active' => 1]);
   $user->create($data);
   \DB::commit();
   return $user;
} catch(\Exception $e) {
   \DB::rollback();
   die($e->getMessage());
   return false;
}

UPDATE 2

I changed the transaction code again and its works:

\DB::beginTransaction();
$user = \App\Models\User::create($data);
$ratePlan = \App\Models\RatePlan::find($data['rate_plan']);
$user->ratePlans()->attach($ratePlan, ['active' => 1]);            \DB::commit();
return $user;

Solution

  • I think you're not loading the rate_plans entity.

    $model->ratePlans()->attach($data['rate_plan'], ['active' => 1]);
    

    In this line $data['rate_plan'] shoud be an instance of your model "rate_plans", and I'm assuming that $model in this situation stand for an entity of your User model

    Also have tried a test without the transaction if the result's is the same ? I give you an example of one of my code which is similar:

    try {
            DB::beginTransaction();
            $group = Group::create($data);
            $employees = User::whereIn('reference', $references)->get();
            $group->employees()->attach($employees);
            $group->save();
            DB::commit();
    } catch(Exception $e) { [...] }
    

    Good luck