我正在嘗試在我的用戶表中實作 created_by 列。
我創建了一個遷移檔案以將新列添加到用戶表中:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->unsignedInteger('created_by')->default(0);
});
}
我有一個具有以下關系的用戶模型:
public function roles()
{
return $this->belongsToMany(Role::class);
}
public function createdBy()
{
return $this->belongsTo(self::class, 'created_by');
}
在 UsersController 中,我有這個方法:
public function view($id)
{
$user = User::with(['roles', 'createdBy'])->where('created_by', Auth::id())->find($id);
return $user;
}
當我回傳用戶變數時,我得到了這個結果:

現在,我想從“created_by”中的“email”訪問值。我試圖這樣做:
return $user->created_by
我得到的是 2 但我想得到的是“ [email protected] ”。
我也嘗試過return $user->created_by->email,但它回傳了一個錯誤,因為我得到的結果return $user->created_by只是一個數字。
我想獲取電子郵件值“ [email protected] ”。
uj5u.com熱心網友回復:
請用 更改createdBy關系函式createdByUser。
這里我們只是更改函式名,以避免列名和關系名沖突。
public function createdByUser()
{
return $this->belongsTo(self::class, 'created_by');
}
所以現在,您可以訪問
$user->createdByUser->email
uj5u.com熱心網友回復:
根據您的 JSON 回應,這應該有效:
$user[0]->created_by->email
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/414198.html
標籤:
