Laravel雄辩的雄辩->多关系分配父

时间:2018-09-28 13:30:36

标签: laravel eloquent

用户模型有很多朋友的主键ID

<?php

namespace App;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
        public function friends()
        {
            return $this->hasMany(Friend::class);
        }
}

朋友模型;属于用户。外键user_id。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Friend extends Model
{
    protected $guarded = ['id'];

    //Make sure birthday is always in right format  
    public function setBirthdayAttribute($value)
    {
        //Put in mysql format
    $this->attributes['birthday'] = date("Y-m-d",strtotime($value));
    }

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

使用以下控制器代码更新用户时出错:

/**
 * Update the specified resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \App\Friend  $friend
 * @return \Illuminate\Http\Response
 */
public function update(Request $request, Friend $friend)
{
        $friend->fill($request->all());
        //Assign user to logged in user...does NOT work; things it is a column
        $friend->user = \Auth::user();
        $friend->save();
        return redirect(action('FriendsController@index'));
}

保存时出现错误消息:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user' in 'field list' (SQL: update `friends` set `last_name` = Muench!!, `updated_at` = 2018-09-28 13:26:01, `user` = {"id":1,"name":"Chris","email":"me@chrismuench.com","email_verified_at":null,"created_at":"2018-09-27 19:52:03","updated_at":"2018-09-27 19:52:03","braintree_id":null,"paypal_email":null,"card_brand":null,"card_last_four":null,"trial_ends_at":null} where `id` = 8)

是否存在无法为用户分配用户对象的原因?我知道我可以设置user_id列,但是如果我可以传递对象,那就太好了。

1 个答案:

答案 0 :(得分:2)

如果要在控制器中分配对象而不是属性,则需要添加以下mutator

public function setUserAttribute($user)
{
   $this->attributes['user_id'] = $user->id;
}

到您的Friend对象。

但是这可能会带来很大的风险,因为关系名称也是user,因此最好使用其他名称(例如friend_user然后使用方法名称setFriendUserAttribute)或使用Eloquent改为使用associate方法:

$friend->user()->associate(\Auth::user());