【问题标题】:How to access other related model data in Laravel?如何在 Laravel 中访问其他相关的模型数据?
【发布时间】:2017-02-01 06:02:10
【问题描述】:

我正在创建一个用户个人资料页面,我想从我的 User 模型和 UserProfile 模型中检索数据。但是我在获得结果时遇到了问题。这是我所做的:

用户模型

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'username',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
    /*
    public function isAdmin() {
        return $this->admin;
    }
    */

    public function profile() {
        return $this->hasOne('App\UserProfile');
    }

}

用户档案模型

class UserProfile extends Model
{
    protected $table = 'user_profile';

    protected $fillable = [
        'phone',
        'address'
    ];

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

然后我访问我的 ProfileController 中的关系

  public function getProfile($username) {

        $user = User::with('user_profile')->where('username', $username)->get();

        dd($user);



    }

我得到了这个错误:

Call to undefined relationship [user_profile] on model [App\User].

user_profile 是我的表名

【问题讨论】:

  • 您的语法不正确。在用户模型中写入用户和用户配置文件之间的关系。然后调用。
  • 我已经有关系了。等会更新我的帖子。

标签: php laravel


【解决方案1】:

使用正确的关系名称:

$user = User::with('profile')->where('username', $username)->first();

此外,在这种情况下,您应该使用first() 方法来获取用户对象。

【讨论】:

  • 所以除了UserUserProfile 我还需要在我的ProfileController 中有一个关系?
  • @Jerielle 您刚刚使用正确的关系代码更新了您的问题,所以现在您只需按照我在回答中的描述使用它。
  • 好吧,我试试 :)
  • 好的,谢谢。我以为with('')里面是表名哈哈。感谢您的帮助
猜你喜欢
  • 2019-09-09
  • 1970-01-01
  • 1970-01-01
  • 2010-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-11
  • 2020-10-02
相关资源
最近更新 更多