首页 文章

Laravel 5关系不起作用?

提问于
浏览
0

在我的应用程序中,我有几个模型:用户和 Profiles . 用户模型仅适用于公司,我的应用仅适用于公司 . 当用户注册时,他们只填写他们的姓名,电子邮件地址和密码 . 我的 Profiles 模型包含公司名称,地址等列 . 我的 Profiles 表单不起作用;不保存到数据库 . 这是设置:

Controller for the form:

public function update($company_name)
{
  $user = User::whereCompanyName($company_name)->firstOrFail();

      $user->fill(Input::all());

      $user->save();

      flash('You have successfully edited your profile');

      return redirect('/');
}

User.php:

public function profile()
{
    return $this->hasOne('Profile');
}

Profile.php:

protected $fillable = ['company_name', 'company_logo', 'company_founded'];

public function user()
{
    return $this->belongsTo('App\User', 'user_id','ID');
}

The Form:

{!! Form::model($user, array('method' => 'PATCH', 'route' => array('profile.update', $user->company_name), 'files' => true)) !!}
{!! Form::hidden('user_id', Auth::user()->id) !!}

    // more fields

<div class="form-group">
    {!! Form::label('company_name', 'Company Name') !!}
    {!! Form::text('company_name', null, ['class' => 'form-control']) !!}
 </div>

{!! Form::submit('Update Profile', ['class' => 'btn btn-primary']) !!}
{!! Form::close() !!}

我的关系是否正确?什么都没有保存到数据库 .

3 回答

  • 1

    您只是更新用户模型和用户模型 . 您还需要在 profile 关系中设置属性:

    $user->update(Input::all());
    $user->profile->update(Input::all());
    

    您的控制器操作也可以稍微整理一下,使用route–model binding注入您的 User 模型实例,并使用服务容器提供 Request 实例,这样您就不会使用 Input façade:

    public function update(User $user, Request $request)
    {
        $user->update($request->all());
        $user->profile->update($request->all());
    
        flash('You have successfully updated your profile.');
    
        return redirect('/');
    }
    
  • 0

    我想评论,但没有足够的声誉:(几天前,我发现这种方法有点问题:

    $user->update(Input::all());
    $user->profile->update(Input::all());
    

    在这种情况下,相关模型中的 mutators (示例中的配置文件)不会被调用(可能是一个错误):

    public function setLoremIpsumAttribute($attr)
    {
        # code
    }
    

    controller 我尝试了另一种方法,它有效:

    $user->update($request->all());
    $user->profile->fill($request->all()['profile'])->push();
    
  • 0

    在Laravel 5中,当你想要与关系链接时,你需要例如(与评论相关的帖子)使用评论中的方法 .

    Post::find(id)->comment()->where(your where statement)
    

    来自Laravel的文件:

    如果需要为检索的注释添加更多约束,可以调用comments方法并继续链接条件:

    $comments = Post::find(1)->comments()->where('title', '=', 'foo')->first();
    

相关问题