Laravel Eloquent 属于:在不使用 echo/die/var_dump 的情况下使用时“尝试获取非对象的属性”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27775459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Eloquent belongsTo: "Trying to get property of non-object" when using without echo/die/var_dump
提问by alexandre
I've just started with Laravel and Eloquent. In my "Receipt"-model, I try to get information about a relationship. As long as I'm using var_dump, I get my information. As soon as I'm just returning the value to use it in a blade view, I get my "Trying to get property of non-object".
我刚刚开始使用 Laravel 和 Eloquent。在我的“收据”模型中,我尝试获取有关关系的信息。只要我在使用 var_dump,我就会得到我的信息。只要我返回值以在刀片视图中使用它,我就会得到“试图获取非对象的属性”。
<?php
class Receipt extends Eloquent {
public function businesspartner() {
return $this->belongsTo('Businesspartner', 'f_businesspartner_id');
}
public function brand() {
return $this->belongsTo('Brand', 'f_brand_id');
}
public function invoice() {
return $this->belongsTo('Invoice', 'f_invoice_id');
}
public function name() {
$name = '';
$bp = $this->businesspartner()->first();
$name = $bp->salutation; // line 21
$name .= ' ';
$name .= $bp->lastname_company;
return $name;
}
}
The error occurs in line 21.
错误发生在第 21 行。
When I now put a var_dump($name);die(); before returning, it prints me my name.
当我现在放一个 var_dump($name);die(); 在返回之前,它会打印我的名字。
What's going wrong here? :(
这里出了什么问题?:(
Regards, Timo
问候,蒂莫
回答by alexandre
SOLUTION
解决方案
As @Jarek Tkaczyk wrote, I was calling the name() method in a loop.
正如@Jarek Tkaczyk 所写,我在循环中调用 name() 方法。
When doing my debug outputs, I got data from my first row. When getting the error, the code was already processing the second row, where the foreign key was null.
在进行调试输出时,我从第一行获取了数据。得到错误时,代码已经在处理第二行,其中外键为空。
Wrapping the problematic part in if(count($this->businesspartner))
helped.
将有问题的部分包装在if(count($this->businesspartner))
帮助中。
For more information about that, Jarek linked that post: https://stackoverflow.com/a/23911985/784588
有关更多信息,Jarek 链接了该帖子:https: //stackoverflow.com/a/23911985/784588