【发布时间】:2020-01-07 23:43:51
【问题描述】:
我正在尝试获取创建帖子的用户名女巫是(问题模型),我不知道有什么问题我尝试了Eager Loading在 laravel 文档中,我检查了这些 Questions 1 Questions 2 并且如果我使用 dd( $problem->user->name); 仍然得到 null 或 Trying to get property 'name' of non-object
我使用 laravel 5.8
ProblemsController.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>
<td>{{ $problem->addedBy }}</td> <!-- Here I get user id (foreign key) I want to get name of that user -->
<td>{{ $problem->comment }}</td>
<td>{{ $problem->solvedBy }}</td>
<td>{{ $problem->solved }}</td>
<td>{{ $problem->created_at->format('d/m/Y H:i') }}</td>
<td class="text-right"> </td>
</tr>
@endforeach
问题表
[...]
public function up()
{
Schema::create('problems', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('accountNumber');
$table->string('accountName');
$table->string('accountEmail');
$table->date('date');
$table->longText('problem');
$table->bigInteger('addedBy')->unsigned()->nullable();
$table->longText('comment')->nullable();
$table->string('solvedBy')->nullable();
$table->boolean('solved');
$table->timestamps();
});
}
[...]
ForingkeyAddedby 迁移
[...]
public function up()
{
Schema::table('problems', function(Blueprint $table){
$table->foreign('addedBy')->references('id')->on('users')->onDelete('set null')->onUpdate('CASCADE');
});
}
[...]
我想使用$problem->user->name 来获取创建帖子的用户的姓名以将其显示在表格中
请帮忙。
谢谢大家。
【问题讨论】:
标签: php laravel laravel-5.8