【问题标题】:Laravel how to get User Profile field from separate tableLaravel如何从单独的表中获取用户配置文件字段
【发布时间】:2020-03-05 21:38:39
【问题描述】:

我是 Laravel 的新手,Eloquent 对我来说是一个相当大的挑战。我有一个 User 和一个 UserProfile 模型和表。 UserProfile 表有 user_id(FK 到用户 ID)、'keyvalue 字段。

我想获取与 user_id 关联的所有 UserProfile 字段的值。这是我的代码,但没有任何效果。我确信我犯了一些愚蠢的错误,但仍在学习:) Laravel。

用户档案模型

class UserProfile extends Model
{
    public $timestamps = FALSE;

    protected $fillable = [
        'user_id',
        'key',
        'value',
    ];

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

用户模型方法

public function profileFields(){

    return $this->hasMany(UserProfile::class);

}

用户配置文件迁移

public function up()
{
    Schema::create('user_profiles', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('user_id')->unsigned();
        $table->string('key', 191);
        $table->longText('value');

        $table->foreign('user_id', 'user_profile_uid_fk')
              ->references('id')
              ->on('users')
              ->onDelete('cascade');

        $table->unique(['user_id', 'key'], 'user_profile_unique_key');
    });
}

我正在尝试使用User::findOrFail(10)->profileFields 获取用户的个人资料字段,但它给了我property not defined 异常。

需要帮助:任何人都可以帮助我让它工作,所以我可以得到所有user_profiles 配置文件表中的字段?

错误输出(修补程序)

>>> User::findOrFail(10)->profileFields

使用消息'SQLSTATE [42S02] 照亮/数据库/查询异常:基础 找不到表或视图:1146 表 'velvetpaper.user_user_profile' 不存在(SQL:选择user_profiles.*, user_user_profile.user_id 作为pivot_user_id, user_user_profile.user_profile_id 作为pivot_user_profile_id 来自 user_profiles 内部连接 ​​user_user_profile user_profiles.id = user_user_profile.user_profile_id 其中user_user_profile.user_id = 10)'

【问题讨论】:

  • 你确定它从那条线上失败了吗?因为当您尝试访问未定义的属性时,Eloquent 不会抛出异常,所以它只会返回 null
  • 你能告诉我们整个错误信息吗?
  • 我正在尝试修补程序。让我发布输出
  • @ChinLeung 我用输出更新了问题。我意识到关系有问题,因为它正在搜索听起来很奇怪的user_user_profile。 :S
  • 您确定在您的App\User 模型中使用了hasMany 关系而不是belongsToMany?如果你使用了 belongsToMany,那么 Laravel 在 user_user_profile 表中搜索是有意义的。

标签: php laravel eloquent


【解决方案1】:

usersuser_profiles 之间的关系是一对多的。

您可能没有重新启动 Tinker,因为您遇到了错误的错误,请不要忘记在修改代码后退出 Tinker。修补程序启动后,代码更改不会影响它。

【讨论】:

  • 那不是真的。一个用户将有多个配置文件字段。如果您查看数据库迁移,则每个记录设置一个数据。
  • 这将只返回一项。
  • 哦,那就重启你的 tinker 控制台吧。
【解决方案2】:

你可以使用 join 来实现这些东西。像这样... 这是查询生成器

$data['profile']=DB::table(usertable)
->where('usertable.id',$id)
->leftjoin('userprofiletable','usertable.id','=','userprofiletable.user_id')
->first();

return view('profile_view',$data)

//查看

$profile->fullname
$profile->sex
$profile->phone
...

【讨论】:

  • 非常感谢您的帮助,但我正在寻找 Eloquent 方式。你能帮我解决这个问题吗?
猜你喜欢
  • 2011-01-14
  • 1970-01-01
  • 1970-01-01
  • 2011-08-06
  • 2014-11-11
  • 1970-01-01
  • 2020-02-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多