因此,我尝试使用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>
我遇到以下错误:
试图获取非对象的属性
答案 0 :(得分:1)
您的查询很有可能在其中返回空值(无记录)。 现在,当您尝试访问其内容(什么都没有)时,会出现错误,提示试图获取非对象的属性
最好打印从模型查询中获得的输出,然后在代码中检查是否有任何记录,然后再处理它们。如下所示:
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
简而言之,这些行将帮助您尽可能地调试问题。
希望它会有所帮助:) 祝你好运
答案 1 :(得分:1)
在您的Assign
模型中:
public function cust()
{
return $this->belongsTo('App\Customer','custid');
}
您正在使用custid
表中的customers
。您需要指定custidno
,这是在custid
表中引用customers
的外键。
将其更新为:
public function cust()
{
return $this->belongsTo('App\Customer','custidno', 'custid');
}
这应该给您正确的记录(如果存在)。然后,您可以检查进一步的逻辑,如果数据不为null,则访问其属性。