I am new to Laravel and Eloquent
is quite a challenge for me to understand. I have a User and a UserProfile model and table. UserProfile table has user_id
(FK to user's id), 'key
, and value
fields.
I want to get the values of all the UserProfile fields associated with the user_id. Here is my code but nothing works. I am sure I am making some stupid mistakes but still learning :) Laravel.
UserProfile Model
class UserProfile extends Model
{
public $timestamps = FALSE;
protected $fillable = [
'user_id',
'key',
'value',
];
public function user()
{
return $this->belongsTo(User::class);
}
}
User Model method
public function profileFields(){
return $this->hasMany(UserProfile::class);
}
UserProfile Migration
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');
});
}
I am trying to get the profile fields for the user using User::findOrFail(10)->profileFields
but it is giving me property not defined
exception.
Need Help: Can anyone help me to make it work so I can get all
user_profiles
fields from the profile table?
Error Output (Tinker)
>>> User::findOrFail(10)->profileFields
Illuminate/Database/QueryException with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table 'velvetpaper.user_user_profile' doesn't exist (SQL: select
user_profiles
.*,user_user_profile
.user_id
aspivot_user_id
,user_user_profile
.user_profile_id
aspivot_user_profile_id
fromuser_profiles
inner joinuser_user_profile
onuser_profiles
.id
=user_user_profile
.user_profile_id
whereuser_user_profile
.user_id
= 10)'
null
. – Chin Leunguser_user_profile
that sounds weired. :S – Code LoverhasMany
relation in yourApp\User
model instead of abelongsToMany
? It would make sense for Laravel to search inuser_user_profile
table if you've used abelongsToMany
. – Chin Leung