php - Laravel 属于试图获取非对象的属性
问题描述
所以我正在尝试使用 BelongsTo 来显示客户详细信息,这是我当前的代码:
我的控制器:
$assignees = assignee::latest()
->whereNull('timeout')
->paginate(10);
return view('assignees.index',compact('assignees'))
->with('i', (request()->input('page', 1) - 1) * 5);
分配表:
$table->string('original_filename')->nullable();
$table->string('custidno')->nullable();
$table->foreign('custidno')->references('custid')->on('customers');
$table->string('cardno')->nullable();
客户表:
Schema::create('customers', function (Blueprint $table) {
$table->increments('id');
$table->string('custid')->index()->unique();
分配模型:
public function cust()
{
return $this->belongsTo('App\Customer','custid');
}
在我看来:我有以下 for 循环,它显示“受让人表”我想用客户名称替换 custidno 字段,取自客户表。
index.blade.php:
<tr>
<td>{{ $assignee->id }}</td>
<td>{{ $assignee->datacenter }}</td>
<td>{{ $assignee->cust->name}}</td>
<td>{{ $assignee->refnumber }}</td>
我收到以下错误:
试图获取非对象的属性
解决方案
您的查询很有可能在其中返回 null(无记录)。现在,当您尝试访问它的内容(什么都没有)时,您会收到错误消息,说尝试获取非对象的属性
最好打印您从模型查询中获得的输出,然后在您的代码中,在处理它们之前检查是否有任何记录。如下所示:
if( count($assignee->cust) ){ // case there are some records against this assignee
{{ $assignee->cust->name}}
}
更好的调试方法来执行以下操作以首先在控制器中查看输出。
echo '<pre>'; // to proper display your output
print_r($assignee); // your object with everything in it
exit; // exit application to see your variable output
只需这些行将帮助您尽可能地调试您的问题。
希望它有所帮助:) 祝你好运
推荐阅读
- java - 如何在 java/kotlin 中编写通用镶木地板
- altium-designer - Altium Designer - 保留旧参考代号
- java - 如何解决此 itext v5 pdf 格式错误?
- node.js - Socket.io 和 React:警告:无法对未安装的组件执行 React 状态更新
- python - 使用 tensorflow 和 keras 进行单值 WaveNet 预测
- javascript - 按等级对有序列表进行排序(javascript)
- intellij-idea - 使用 jetbrains IDE(Intellij 或 Rider)登录 GitHub 企业
- r - 上传数据文件并为每列创建复选框和文本输入和下拉列表的闪亮应用程序
- android - RxJava:如果返回 Single 的函数抛出异常,如何捕获错误?
- javascript - 获取请求标头未在 chrome (v90.0.44) 中发送 cookie,在 Firefox(v88.0) (JS) 中工作