我正在嘗試獲取創(chuàng)建帖子女巫的用戶名是(問題模型),我不知道出了什么問題我在 laravel 文檔中嘗試了Eager Loading ,我已經檢查了這些問題 1 問題 2并且仍然為 null 或者Trying to get property 'name' of non-object如果我用dd( $problem->user->name);我使用 laravel 5.8問題Controller.phpnamespace App\Http\Controllers;use Illuminate\Http\Request;use App\User;use App\Problems ;use App\Rules\Checkbox;use Validator;[...] public function index() { //$users_row_num = User::count(); // $problems_row_num = Problems::count(); $problems = Problems::all(); foreach ($problems as $problem) { /* Here should get name to send with view but I get null * if I try $problem->user->name I get Trying to get property 'name' of non-object because user is null */ dd( $problem->user); } return view('problems.index', [ 'problems' => $problem, 'user_numder' => $users_row_num, 'problem_number' => $problems_row_num, ]); }[...]Problems.php(模型)<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class Problems extends Model{ public function user() { return $this->belongsTo('App\User'); }}Usre.php(模型)<?phpnamespace App;use Illuminate\Notifications\Notifiable;use Illuminate\Contracts\Auth\MustVerifyEmail;use Illuminate\Foundation\Auth\User as Authenticatable;class User extends Authenticatable{[...] public function problem() { return $this->hasMany('App\Problems'); }[...]}index.blade.php @foreach ($problems as $problem) <tr> <td>{{ $problem->accountNumber }}</td> <td>{{ $problem->accountName }}</td> <td>{{ $problem->accountEmail }}</td> <td>{{ $problem->date }}</td> <td>{{ $problem->problem }}</td>我想用來$problem->user->name獲取創(chuàng)建帖子的用戶的名稱以將其顯示在表格中
1 回答

神不在的星期二
TA貢獻1963條經驗 獲得超6個贊
您的用戶模型正在問題表中尋找一個user_id字段以使關系正常工作。Laravel 使用模型名稱 + '_id' 自動為模型關系創(chuàng)建使用蛇形案例的關系。
如果您將問題表上的外鍵更改為,user_id而不是addedBy,這將按原樣工作。
或者,如果您希望保留addedBy密鑰,則需要告訴 Laravel 您使用的是非標準密鑰。因此,在您的用戶模型上:
public function problem()
{
return $this->hasMany('App\Problems', 'addedBy');
}
應該做的伎倆。請參閱此處的文檔。
不幸的是,您可能還沒有在桌子上定義實際的 FK。在foreign指定之前,我希望看到如下內容:
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
或者如果使用更新版本的 Laravel:
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
遷移文檔在此處適用于V6 。
- 1 回答
- 0 關注
- 115 瀏覽
添加回答
舉報
0/150
提交
取消