php - 尝试在 null 上读取属性“client_name”
问题描述
背景:我不熟悉 PHP,自从上一个开发人员离开后,我就一直在创建一个环境。
我的错误resources\views\layouts\app.blade.php
<div class="user-wrapper">
<img class="user-img" src="{{ asset('images/user-circle.svg')}}" alt="User"/>
<div class="user-info">
<h3>{{ Auth::user()->name}}</h3>
<p> {{ Auth::user()->email}}</p>
<p> {{ Auth::user()->client->client_name}}</p>
</div>
</div>
这是我的客户模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Client extends Model
{
use HasFactory;
use SoftDeletes;
protected $fillable = [
'client_name',
'description',
];
}
和用户模型
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
'client_id',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function client(){
return $this->hasOne(Client::class, 'id', 'client_id');
}
}
我可以从我的数据库中获取名称和电子邮件,但对于客户端它以某种方式返回 null。我还验证了我可以从客户端表中获取数据。
编辑:我按照建议在客户端模型中添加了以下几行,但我仍然得到
public function client(){
return $this->hasOne(Client::class, 'client_id', 'id');
}
解决方案
我通过运行解决了这个问题:
php artisan migrate:reset
php artisan migrate
推荐阅读
- c# - Why don't the following expressions trigger "The result of the expression is always false ..."?
- ruby-on-rails - Rubocop 唯一性验证应该使用唯一索引,在从某些特定值开始的值中
- javascript - 如何将“function init()”与我在 JavaScript 中的代码一起使用?
- javascript - 使用 JavaScript 将 href 添加到锚点
- python - 为什么执行此过程时我的笔记本电脑有时会死机
- html - 隐藏带有溢出的下拉菜单:隐藏
- pytorch - 无法在 Google Colab 上安装 Pytorch Lightning Flash
- google-chrome - 我可以使用新的 WebCodecs api 在 Chrome94+ 中进行快速简单的 remuxing 吗?
- python-3.x - ValueError:int() 的无效文字,基数为 10:'Gene1'
- c - 我正在尝试基于流程图制作 C 代码,但我在执行此操作时遇到了麻烦