Laravel 5与表单绑定有一种关系 [英] Laravel 5 Has One Relationship with Form Binding

查看:62
本文介绍了Laravel 5与表单绑定有一种关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了相当不错的两天时间来做一件简单而又小的事情.我有一个名为User的模型,它具有一个用户注释关系.

I have spent a pretty good two days on something so simple and small. I have a model called User which has one user note relationship.

在用户模型侧,我定义了一个belongsTo关系,然后用户模型定义了一个hasOne关系.

On the User model's side I have a belongsTo relationship defined and then the user's model defines a hasOne side of relationship.

我正在使用的表单绑定到$user模型,而UserNote模型有自己的表,该表映射到具有user_id的用户.

The form I am using binds to $user model meanwhile the UserNote model has its own table that maps to the user with user_id.

我一直在尝试获取右下方显示的内容;

I have been trying to get what is shown below right;

{{ Form::textarea($user->notes, null , [ 'class' => 'form-control', 'placeholder' => 'Note Content']) }}

有人在那里帮助我解决这个问题吗?b我所需要的只是能够添加便笺,并且如果用户还没有便笺,我应该不会收到错误提示,因为如果我按如下所示操作,则会收到错误提示:

Somebody out there to help me figure this out?b All I need is to be able to add a note and if a user has no note yet I should not be getting errors because if I do as shown below I get an error:

{{ Form::textarea('UserNote[content]',... }}

您的建议将不胜感激.

class User{
 ...
 public function note()
 {
    return $this->belongsTo(UserNote::class);
  }
}

class UserNote{
 protected $fillable = ['content', 'user_id'];
...
public function user()
{
    return $this->hasOne(User::class, 'user_id');
  }
}

当然不应该首先在$fillable中使用user_id,因为这仅意味着我可以手动更新此表,而我希望从控制器自动完成所有工作以形成表单绑定.

Surely the user_id in $fillable shouldn't be there in the first place because this only means I can update this table manually whereas I want everything done automatically from controller to form binding.

推荐答案

首先,您做错了关系.

First of all, you're doing the relationship wrong.

  • 用户有一个UserNote
  • UserNote属于用户
  • User hasOne UserNote
  • UserNote belongsTo User

因此,您必须交换那些相应模型上的关系.
其次,表单的文本区域具有如下参数列表:

So, you've to swap the relations on those corresponding models.
Secondly, The form's textarea has the parameter list like:

public function textarea($name, $value = null, $options = []){}

因此,第一个参数显然是 form_name .第二个参数将是输入的.您做错了.
就您而言,这应该是(我认为)

So, the first parameter is obviously the form_name. second parameter will be the value of the input. You're doing this wrong.
In your case, that should be ( as I think )

{{ Form::textarea('user_note', $user->note , [ 'id' => 'user_note', 'class' => 'form-control', 'placeholder' => 'Note Content']) }}

修改
属性 note 是方法名称,您之前写的像 notes 一样,该方法不存在. 编辑结束
希望这可以帮助.编码愉快!

Edit
The property note is the method name, you're previously writing like notes, the method didn't exist. Edit Ends
Hope this helps. Happy coding!

这篇关于Laravel 5与表单绑定有一种关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆