【问题标题】:Laravel Belongs to trying to get property of Non objectLaravel 属于试图获取非对象的属性
【发布时间】:2019-07-12 19:26:34
【问题描述】:

所以我正在尝试使用 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>

我收到以下错误:

试图获取非对象的属性

【问题讨论】:

  • 试试 {{ $assignee->cust()->name }}
  • 我可以查看您的查找查询吗?
  • 您必须在查询中指定“with”
  • 可能你的cust 属性返回null...!你检查了吗?
  • @KaushikMakwana,我已经从我的控制器中包含了一个 sn-p。

标签: php laravel eloquent


【解决方案1】:

在您的Assign 模型中:

public function cust()
{
    return $this->belongsTo('App\Customer','custid');
}

您正在使用custid,它位于customers 表内。您需要指定custidno,它是在customers 表中引用custid 的外键。

更新为:

public function cust()
{
    return $this->belongsTo('App\Customer','custidno', 'custid');
}

如果存在,那应该会为您提供正确的记录。然后你可以检查进一步的逻辑,如果数据不为空,然后访问它的属性。

【讨论】:

  • 非常感谢您解决这个问题!它现在正在返回客户全名:)
【解决方案2】:

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

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

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

【讨论】:

  • 你是对的,它返回 null,但我不确定为什么。我已按照所有教程来识别受让人表中的外键。
  • @Abdul 你是在受让人表中还是从客户模型关系中获得 NULL?尝试在不分页的情况下获取记录以便理解
  • 对于这一行 {{ $assignee->cust->name}} 有可能受让人客户 ID 为空,因此当我们尝试访问所属客户名称时, 发生错误
  • 您可能需要将关系外键更新为不为空,以确保有针对受让人的记录
猜你喜欢
  • 2015-09-22
  • 2017-03-20
  • 2014-03-25
  • 2015-01-25
  • 2014-06-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多