【发布时间】:2020-03-05 21:38:39
【问题描述】:
我是 Laravel 的新手,Eloquent 对我来说是一个相当大的挑战。我有一个 User 和一个 UserProfile 模型和表。 UserProfile 表有 user_id(FK 到用户 ID)、'key 和 value 字段。
我想获取与 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_profileuser_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表中搜索是有意义的。