![](/img/trans.png)
[英]Store a user's “rating” in profile or constantly run SQL queries to get average from separate table
[英]Laravel how to get User Profile field from separate table
我是新來的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
照射/數據庫/ QueryException與消息“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
onuser_profiles
.id
=user_user_profile
.user_profile_id
whereuser_user_profile
.user_id
= 10)'
你可以使用 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
...
users
和user_profiles
之間的關系是一對多的。
您可能沒有重新啟動 Tinker,因為您收到錯誤錯誤,請不要忘記在代碼修改后退出 Tinker。 一旦 tinker 啟動,代碼更改不會影響它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.