表单更新数据库模型记录的关系



我想知道如何使用前端表单更新模型的关系。我查看了文件,发现:

或者,您可以使用主键设置关系,这 在使用 HTML 表单时很有用。

// 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();

用于更新关系的后端窗体工作正常。这是我的代码,我在其中获取 ID 作为值,但它似乎不会影响关系字段。帮助将非常感谢!

$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();

这是数据透视表:

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');
}
}

下面是模型关系:

public $hasOne = [
'client' => 'BrandonInvoiceModelsClients'
];

这是前端形式:根据其 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>

生成器中关系的图像。

我认为您需要添加属于关系而不是hasOne

public $belongsTo = [
'client' => 'BrandonInvoiceModelsClients'
];

使用以下命令设置客户端后:

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

您需要使用以下方法保存更改:

$project->save();

假设您的表和模型已正确设置,上述方法应该可以正常工作。如果没有,则需要发布表的结构和其余代码。

最新更新