我正在尝试获取创建帖子女巫的用户名是(问题模型),我不知道出了什么问题我在 laravel 文档中尝试了Eager Loading ,我已经检查了这些问题 1 问题 2并且仍然为 null 或者Trying to get property 'name' of non-object如果我用dd( $problem->user->name);
我使用 laravel 5.8
问题Controller.php
namespace 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(模型)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Problems extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
Usre.php(模型)
<?php
namespace 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获取创建帖子的用户的名称以将其显示在表格中
神不在的星期二