简体   繁体   中英

Form Update Database Model Record's Relationship

I want to know how to up date a model's relationship using a frontend form. I looked at the documents and found:

Alternatively you may set the relationship using the primary key, this is useful when working with HTML forms.

// Assign to author with ID of 3
$post->author = 3;

// Assign comments with IDs of 1, 2 and 3
$post->comments = [1, 2, 3];

$post->save();

the backend form to update the relationship works fine. This is my code and where I am getting ID as a value but it doesn't seem to affect the relationship field. Help would be great thanks!

    $project = new Projects(); 
    $project->name = Input::get('name');
    $project->price = Input::get('price');
    $project->work = Input::get('work');
    $project->client = Input::get('client');
    $project->slug = $slug;
    $project->save();
    Flash::success('Estimate Added!');
    return Redirect::refresh();

This is the Pivot Table:

public function up()
    {
        Schema::create('brandon_invoice_ip', function($table)
        {
            $table->engine = 'InnoDB';
            $table->integer('invoices_id');
            $table->integer('projects_id');
            $table->primary(['invoices_id','projects_id']);
        });
    }

    public function down()
    {
        Schema::dropIfExists('brandon_invoice_ip');
    }
}

Here is the model relationship:

public $hasOne = [
        'client' => 'Brandon\Invoice\Models\Clients'
    ];

This is the front end form: The values are correct according to their ID.

<div class="uk-margin uk-first-column">
    <label class="uk-form-label" for="client">Client</label>
    <div class="uk-form-controls">
        <select class="uk-select" name="client">
          <option value="1">Brandon</option>
          <option value="2">Sanitary Ostomy System</option>
        </select>
    </div>
</div>

Image of the relationship in the builder.

After you set the client using:

$project->client = Input::get('client');

You need to save the changes using:

$project->save();

Assuming your tables and models have been setup correctly, the above should work. If it does not, you need to post the structure of your tables and the rest of your code.

I think you need to add belongsTo relationship instead of hasOne

public $belongsTo = [
    'client' => 'Brandon\Invoice\Models\Clients'
];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM