Reputation: 8348
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.
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');
});
}
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?
>>> 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)'
Upvotes: 0
Views: 1837
Reputation: 17206
The relation between users
and user_profiles
is a one to many.
You might have not restarted Tinker since you are getting the wrong error, dont forget to exit Tinker after the modification in the code. Once tinker is started, code changes wont affect it.
Upvotes: 0
Reputation: 902
you can use join to implement this stuff. like this... this is query builder
$data['profile']=DB::table(usertable)
->where('usertable.id',$id)
->leftjoin('userprofiletable','usertable.id','=','userprofiletable.user_id')
->first();
return view('profile_view',$data)
//view
$profile->fullname
$profile->sex
$profile->phone
...
Upvotes: 0