簡體   English   中英

Laravel 如何從單獨的表中獲取用戶配置文件字段

[英]Laravel how to get User Profile field from separate table

我是新來的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字段嗎?

錯誤輸出(Tinker)

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

照射/數據庫/ QueryException與消息“SQLSTATE [42S02]:基表或視圖未找到:1146表'velvetpaper.user_user_profile'不存在(SQL:選擇user_profiles 。*, user_user_profileuser_idpivot_user_iduser_user_profileuser_profile_idpivot_user_profile_iduser_profiles內部加入user_user_profile on user_profiles . id = user_user_profile . user_profile_id where user_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
...

usersuser_profiles之間的關系是一對多的。

您可能沒有重新啟動 Tinker,因為您收到錯誤錯誤,請不要忘記在代碼修改后退出 Tinker。 一旦 tinker 啟動,代碼更改不會影響它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM