【问题标题】:How to call second model in form model binding laravel?如何在表单模型绑定 laravel 中调用第二个模型?
【发布时间】:2020-01-29 20:58:59
【问题描述】:

所以我有一个使用模型投标在表单内显示值的表单,如下所示:

{!! Form::model($teacher, ['method' => 'PUT', 'route' => ['admin.teachers.update', $teacher->user_id]]) !!}

{!! Form::label('cpf', 'CPF*', ['class' => 'control-label']) !!}
{!! Form::text('cpf', old('cpf'), ['class' => 'form-control') !!}

{!! Form::close() !!}

问题是,Teacher 模型 'belongsTo' 是一个 User 模型,它存储 Name、Email 等,而 Teacher 模型存储 CPF、Phone、Sex 等字段。

我正在尝试制作一个更新表单,但我可以通过说出 old('name') 来显示值,我必须这样做,以便我可以从 User 对象访问名称

{{ Form::text('name', $teacher->user->name, ['class' => 'form-control']) }}

问题是这不能正常工作,当我执行更新时,即使我没有更改字段电子邮件中的值,它也会像我已经更改一样运行,那么我该如何解决这个问题?我尝试使用 old() 调用 $teacher->user->name 但它没有用

{{ Form::text('name', old($teacher->user->name), ['class' => 'form-control') }}

【问题讨论】:

  • 必须与teacheruser 建立关系?laravel.com/docs/6.x/eloquent-relationships
  • 是的,两种模型都存在这种关系
  • 如果teacher belogsTo user 那么它会工作,如果很多那么它不会,你得到什么错误。?
  • 它认为你应该试试这个old($teacher->user->name) ?? $teacher->user->name
  • 请确保您的关系是一对多的,否则您将在 $teacher->user 上有一个集合。我的意思是老师 hasMany(users) 和 user belongsTo(teacher)

标签: php laravel model-binding


【解决方案1】:

试试这个

{{ Form::text('name', old('name')?? $teacher->user->name, ['class' => 'form-control') }}

如果存在则打印old值,否则打印$teacher->user->name

【讨论】:

    猜你喜欢
    • 2013-05-28
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    • 1970-01-01
    • 2013-07-13
    • 2014-12-02
    • 2017-06-27
    • 2013-11-02
    相关资源
    最近更新 更多