问题
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.
On the User model's side I have a belongsTo relationship defined and then the user's model defines a hasOne side of relationship.
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']) }}
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]',... }}
Your advice would be appreciated.
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');
}
}
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.
回答1:
First of all, you're doing the relationship wrong.
- 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 = []){}
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']) }}
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!
来源:https://stackoverflow.com/questions/38634074/laravel-5-has-one-relationship-with-form-binding