【问题标题】:Form Update Database Model Record's Relationship表单更新数据库模型记录的关系
【发布时间】:2018-10-12 07:47:28
【问题描述】:

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

或者,您可以使用主键设置关系,这 在处理 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' => 'Brandon\Invoice\Models\Clients'
    ];

这是前端表单:根据 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.

【问题讨论】:

  • 您是否使用Input::get('client') 获取客户端ID?
  • 我更新了我的代码,是的,我验证了客户端的值是正确的。

标签: php laravel-5 octobercms


【解决方案1】:

我认为你需要添加belongsTo关系而不是hasOne

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

【讨论】:

  • 感谢您的建议。我将其更改为 $belongsTo 并将 client_id 字段添加到表中。那行得通,我需要再次查看文档以完全了解关系。
  • 我很高兴这有效,是的,我还认为您必须重新访问关系工作流程才能更好地理解它。只是一个请求,你能支持我的回答吗?谢谢
【解决方案2】:

设置客户端后使用:

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

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

$project->save();

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

【讨论】:

  • 我更新了我的代码以显示大部分内容。我确实有 $project->save()。所有其他字段都可以很好地填写表格。
猜你喜欢
  • 2014-11-13
  • 1970-01-01
  • 2018-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多