首页 > 解决方案 > 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>

我收到以下错误:

试图获取非对象的属性

标签: phplaraveleloquent

解决方案


您的查询很有可能在其中返回 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

只需这些行将帮助您尽可能地调试您的问题。

希望它有所帮助:) 祝你好运


推荐阅读