【问题标题】:Laravel Eloquent one --> many relationship assigning parentLaravel Eloquent 一-> 多关系分配父
【发布时间】:2018-09-28 21:45:09
【问题描述】:

用户模型有很多朋友主键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 列,但如果我可以传递对象,那就太好了。

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

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

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

    到您的Friend 对象。

    但是这可能是相当冒险的,因为关系名称也是user,所以最好使用其他名称(例如friend_user然后方法名称setFriendUserAttribute)或使用Eloquent associate方法代替:

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

    【讨论】:

    • 我没有更改任何代码并且能够使用 $friend->user()->associate(\Auth::user());。我不能做 $friend->user->associate(\Auth::user()); 有什么原因吗?我想我不明白为什么我不能使用魔法属性而必须使用方法。
    • 是的,当您处理关系时,您使用user()。但是当你想显示它时,根据关系类型,你可以使用$friend-&gt;user()-&gt;first()$friend-&gt;users()-&gt;get(),但在这种情况下,你也可以使用“快捷方式”,如$friend-&gt;user$friend-&gt;users
    猜你喜欢
    • 2013-02-09
    • 1970-01-01
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    • 2015-05-19
    • 2019-06-13
    • 2017-04-20
    • 2016-07-27
    相关资源
    最近更新 更多