Laravel 4重复数据库条目

时间:2013-11-29 13:53:55

标签: php mysql database laravel-4

我有两个模型用于用户,另一个用于许可。如果用户是使用牙医或牙科卫生师,那么他们将需要输入他们的许可证信息。在我的用户模型中,我有一条规则,即一个许可属于一个用户。在我的许可证模型中,我有一条规则,说许可证属于用户。当我提交具有正确usertype的用户的许可证号,状态和到期日期时,他们的信息就会存储在数据库中。 我遇到的问题是当同一个用户回到他们的个人资料和更新时,例如他们的到期日期然后由于某种原因在数据库中有该用户的两个条目。

修改后的控制器

            if( $user->usertype == 'dental hygienist' || $user->usertype == 'dentist'  && !isset($license_num ) && !isset($license_state) && !isset($license_exp)) {

                $license = new License();
                $license->user_id = $id;
                $license->temp_id = $id;
                $license->license_expiration_date = Input::get('expiration_date');
                $license->license_number = Input::get('license_number');
                $license->license_state = Input::get('license_state');

                $license->save();
            }else if ($user->usertype == 'dental hygienist' || $user->usertype == 'dentist'  && isset($license_num ) && isset($license_state) && isset($license_exp)){
                $license = License::find($id);
                $license->license_expiration_date = Input::get('expiration_date');
                $license->license_number = Input::get('license_number');
                $license->license_state = Input::get('license_state');

                $license->save();
            }

查看

@extends('layouts.master')

@section('content')
<div class="container profile-wrapper" style="position: relative;top:170px;">
        <div class="col-lg-8 profile-content">
            <div class="panel panel-default">
                <div class="panel-heading">{{ucwords($user->firstname)}}, Update Your Profile Below</div>
                @if($errors->any())
                <div class="alert alert-error">
                    <a class="close" data-dismiss="alert" href="#" aria-hidden="true">&times;</a>
                    {{ implode('', $errors->all('<li class="error"><b>:message</b></li>')) }}
                </div>
                @endif
                <div class="panel-body">

                    {{ Form::model($user, array('url' => array('user/profile/update', $user->id), 'method' => 'PUT', 'class'=>'form-inline edit-form')) }}

                    <fieldset>
                        <legend>Personal Information</legend>
                            <div class="form-group">
                                <label for="firstname">First Name</label>
                                {{ Form::text('firstname', null, array('class' => 'form-control input-sm')) }}
                            </div>

                            <div class="form-group">
                                <label for="lastname">Last Name</label>
                                {{ Form::text('lastname', null, array('class' => 'form-control input-sm')) }}
                            </div>

                        <div class="form-group">
                            <label for="zipcode">Zip Code</label>
                            {{ Form::text('zipcode', null, array('class' => 'form-control input-sm')) }}

                        </div>


                    </fieldset>



                    <fieldset>
                        <legend>Professional Information</legend>


                        <div class="form-group">
                            <label for="experience">Years Experience</label>
                            {{ Form::text('temp_experience', null, array('class' => 'form-control input-sm')) }}
                        </div>


                        <div class="form-group">
                            <label for="hourlyrate">Hourly Rate</label>
                            {{ Form::text('temp_hourly_rate', null, array('class' => 'form-control input-sm')) }}
                        </div>

                        <div class="form-group temp_travel_input">
                            <label for="zipcode">Willingness to Travel</label>
                            {{ Form::text('temp_travel', null, array('class' => 'form-control  input-sm')) }}
                        </div><!-- end .form-group -->

                        <!-- conditional statement for different temp types -->

                        <div class="form-group mtop-20">
                            <label for="temp_software_experience">Software Experience:</label><br>
                            <label class="checkbox-inline">
                                <input name="software[]" type="checkbox"  value="Practiceworks" <?php $software = explode(',', $user->temp_software_experience); if(in_array("Practiceworks",$software)) echo "checked"; ?>> Practiceworks
                            </label>
                            <label class="checkbox-inline">
                                <input name="software[]" type="checkbox"  value="Softdent" <?php $software = explode(',', $user->temp_software_experience); if(in_array("Softdent",$software)) echo "checked"; ?>> Softdent
                            </label>
                            <label class="checkbox-inline">
                                <input name="software[]" type="checkbox"  value="Ortho trac" <?php $software = explode(',', $user->temp_software_experience); if(in_array("Ortho trac",$software)) echo "checked"; ?>> Ortho trac
                            </label>
                            <label class="checkbox-inline">
                                <input name="software[]" type="checkbox"  value="Dentrix" <?php $software = explode(',', $user->temp_software_experience); if(in_array("Dentrix",$software)) echo "checked"; ?>> Dentrix
                            </label>
                            <label class="checkbox-inline">
                                <input name="software[]" type="checkbox" value="Easy Dental" <?php $software = explode(',', $user->temp_software_experience); if(in_array("Easy Dental",$software)) echo "checked"; ?>> Easy Dental
                            </label>
                            <label class="checkbox-inline">
                                <input name="software[]" type="checkbox" value="Eaglesoft" <?php $software = explode(',', $user->temp_software_experience); if(in_array("Eaglesoft",$software)) echo "checked"; ?>> Eaglesoft
                            </label>
                            <label class="checkbox-inline">
                                <input name="software[]" type="checkbox" value="Other" <?php $software = explode(',', $user->temp_software_experience); if(in_array("Other",$software)) echo "checked"; ?>> Other
                            </label>

                        </div><!-- end .form-group -->


                    </fieldset>

                    @if($user->usertype == "dental hygienist")

                    <div class="form-group mtop-20">
                        <label for="temp_software_experience">Anesthesia Certified:</label><br>
                        <label class="radio-inline">
                            <input name="answer[]" type="radio"  value="1" > Yes
                        </label>
                        <label class="checkbox-inline">
                            <input name="answer[]" type="radio"  value="0"> No
                        </label>

                    </div><!-- end .form-group -->

                    <fieldset>
                        <legend>License Information</legend>

                        <div class="form-group">
                            <label for="license_number">License Number</label>
                            <input type="text" class="form-control input-sm"  name="license_number" value="@if($user->license){{$user->license->license_number}}@endif" required/>
                        </div>


                        <div class="form-group">
                            <label for="license_state">License State</label>
                            <select name="license_state" class="form-control input-sm">
                                <option selected value="@if($user->license){{$user->license->license_state}}@endif">@if($user->license){{$user->license->license_state}}@endif</option>
                                <option value="">-- UNITED STATES --</option>
                                <option value="Alabama">Alabama</option>
                                <option value="Alaska">Alaska</option>
                                <option value="Arizona">Arizona</option>
                                <option value="Arkansas">Arkansas</option>
                                <option value="California">California</option>
                                <option value="Colorado">Colorado</option>
                                <option value="Connecticut">Connecticut</option>
                                <option value="Delaware">Delaware</option>
                                <option value="Florida">Florida</option>
                                <option value="Georgia">Georgia</option>
                                <option value="Hawaii">Hawaii</option>
                                <option value="Idaho">Idaho</option>
                                <option value="Illinois">Illinois</option>
                                <option value="Indiana">Indiana</option>
                                <option value="Iowa">Iowa</option>
                                <option value="Kansas">Kansas</option>
                                <option value="Kentucky">Kentucky</option>
                                <option value="Louisiana">Louisiana</option>
                                <option value="Maine">Maine</option>
                                <option value="Maryland">Maryland</option>
                                <option value="Massachusetts">Massachusetts</option>
                                <option value="Michigan">Michigan</option>
                                <option value="Minnesota">Minnesota</option>
                                <option value="Mississippi">Mississippi</option>
                                <option value="Missouri">Missouri</option>
                                <option value="Montana">Montana</option>
                                <option value="Nebraska">Nebraska</option>
                                <option value="Nevada">Nevada</option>
                                <option value="New Hampshire">New Hampshire</option>
                                <option value="New Jersey">New Jersey</option>
                                <option value="New Mexico">New Mexico</option>
                                <option value="New York">New York</option>
                                <option value="North Carolina">North Carolina</option>
                                <option value="North Dakota">North Dakota</option>
                                <option value="Ohio">Ohio</option>
                                <option value="Oklahoma">Oklahoma</option>
                                <option value="Oregon">Oregon</option>
                                <option value="Pennsylvania">Pennsylvania</option>
                                <option value="Rhode Island">Rhode Island</option>
                                <option value="South Carolina">South Carolina</option>
                                <option value="South Dakota">South Dakota</option>
                                <option value="Tennessee">Tennessee</option>
                                <option value="Texas">Texas</option>
                                <option value="Utah">Utah</option>
                                <option value="Vermont">Vermont</option>
                                <option value="Virginia">Virginia</option>
                                <option value="Washington">Washington</option>
                                <option value="West Virginia">West Virginia</option>
                                <option value="Wisconsin">Wisconsin</option>
                                <option value="Wyoming">Wyoming</option>
                            </select>
                        </div>

                            <div class="form-group mtop-20">
                                <label for="experience">Expiration Date</label>

                                <div class="input-group">
                                    <span class="input-group-addon input-sm"><span class="glyphicon glyphicon-calendar"></span></span>
                                    <input type="date" class="form-control input-sm" name="expiration date" value="@if($user->license){{$user->license->license_expiration_date}}@endif" required>
                                </div>
                            </div>
                    </fieldset>
                    @endif


                    {{Form::hidden('uid', $user->id)}}
                    <div class="form-group">
                        {{ Form::submit('Update', array('class'=>'btn btn-primary form-control'))}}
                    </div>

                        {{ Form::close() }}

                    </div><!-- end .panel-body -->

                </div><!-- end .panel/default -->

            </div><!-- end .profile-content -->

            <div class="col-lg-4">
                image
            </div>
        </div><!-- end .container/profile-wrapper -->
@stop

控制器

public function update($id)
{

    // validate
    // read more on validation at http://laravel.com/docs/validation
    $rules = array(
        'firstname' => 'required|min:3|alpha',
        'lastname' => 'required|min:3|alpha',
        'zipcode' => 'required|min:5|numeric',
        'temp_experience' => 'required|min:1|max:50|numeric',
        'temp_travel' =>   'required|numeric',
        'temp_hourly_rate' => 'required|numeric|min:10'
    );
    $validator = Validator::make(Input::all(), $rules);


    // process the login
    if ($validator->fails()) {
        return Redirect::to('user/profile/' . $id . '/edit')
            ->withErrors($validator)
            ->withInput();
    } else {
        $software_checked = Input::get('software');
        if(is_array($software_checked))
        {
            $imploded_software = implode(',', $software_checked);
        }


        // store
        $user = User::find($id);

        $license_num = Input::get('license_number');
        $license_state = Input::get('license_state');
        $license_exp = Input::get('expiration_date');

        $user->firstname       = Input::get('firstname');
        $user->lastname      = Input::get('lastname');
        $user->zipcode = Input::get('zipcode');
        $user->temp_experience = Input::get('temp_experience');
        $user->temp_travel = Input::get('temp_travel');
        $user->temp_hourly_rate = Input::get('temp_hourly_rate');
        $user->temp_software_experience = $imploded_software;
        if(isset($license_num) && isset($license_state) && isset($license_exp)){
            $user->approved = 1;
        }
        else{
            $user->approved = 0;
        }
        if( $user->save() ) {
            if( $user->usertype == 'dental hygienist' || $user->usertype == 'dentist'  && !$user->license->temp_id ) {

    could this be the problem?->$license = new License();
                $license->user_id = $id;
                $license->temp_id = $id;
                $license->license_expiration_date = Input::get('expiration_date');
                $license->license_number = Input::get('license_number');
                $license->license_state = Input::get('license_state');

                $license->save();
            }

                // redirect
                Session::flash('message', 'Successfully updated profile!!');
                return Redirect::to('user/profile/'.$id.'');
        }
    }

}

用户模型

<?php

use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {



    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = array('password');

    /**
     * Get the unique identifier for the user.
     *
     * @return mixed
     */
    public function getAuthIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Get the password for the user.
     *
     * @return string
     */
    public function getAuthPassword()
    {
        return $this->password;
    }

    /**
     * Get the e-mail address where password reminders are sent.
     *
     * @return string
     */
    public function getReminderEmail()
    {
        return $this->email;
    }


    public static function getTemps()
    {

       // Create a array of allowed types.
        $types = array('dental hygienist', 'dentist', 'dental assistance');

        // Get what type the user selected.
        $type = Input::get('temptype');

        //Get user location
        //$location = Input::get('zipcode');


        // Make sure it is a valid type.
        if(!in_array($type, $types))
        {
            return App::abort(500, "Invaild temptype.");
        }

      $temps =  DB::table('users')
            ->join('availability', 'users.id', '=', 'availability.userid')
            ->select('users.id', 'users.firstname', 'users.lastname', 'users.zipcode', 'users.salary', 'availability.dateavailable')
            ->where('usertype', $type)
           //->where('zipcode', $location)
            ->get();

        return $temps;
    }

    public function license()
    {
        return $this->hasOne('License');
    }

许可证模型

<?php

class License extends Eloquent {


    protected  $table = 'temps_license';

    public function user()
    {
        return $this->belongsTo('User');
    }



}

1 个答案:

答案 0 :(得分:0)

更改

$license = new License();
$license->user_id = $id;
$license->temp_id = $id;
$license->license_expiration_date = Input::get('expiration_date');
$license->license_number = Input::get('license_number');
$license->license_state = Input::get('license_state');

$license->save();

使用

$license = $user->license;
$license->temp_id = $id;
$license->license_expiration_date = Input::get('expiration_date');
$license->license_number = Input::get('license_number');
$license->license_state = Input::get('license_state');

$license->save();

您还可以修改迁移文件以使其具有$table->unsignedInteger('user_id')->unique(),如果您想确保不创建重复项