[英]Laravel eloquent model relationship don't work on blade template
I have two tables: 我有两个表:
Persons
id, name, foto_id
and 和
Fotos
id, url
On Person
model, I added: 在
Person
模型上,我添加了:
public function foto() {
return $this->hasOne("App\\Foto","id","foto_id");
}
Note that I needed to escape the
\\F
...请注意,我需要转义
\\F
...
When i try to {{ $person->foto->url }}
, I get the "trying to access property of non-object" error . 当我尝试
{{ $person->foto->url }}
,出现“尝试访问非对象属性”错误 。 If I {{ print_r($person->foto()) }}
I get just 1
... 如果我
{{ print_r($person->foto()) }}
我只会得到1
...
I followed the laravel docs, and this tutorial 我关注了laravel文档和本教程
This is a project I'm creating to learn Laravel, so any helpful advice is appreciated! 这是我为学习Laravel而创建的一个项目,因此感谢您提供任何有用的建议!
Edit: 编辑:
In artisan tinker
, $person->foto->url
work as intended, returns the Foto
object just fine... 在
artisan tinker
,按预期的$person->foto->url
工作,返回Foto
对象就好了...
You need to use the belongsTo
function instead of the hasOne
. 您需要使用
belongsTo
函数而不是hasOne
。
If you create a Foto
model, there you'll need a hasMany
function. 如果创建
Foto
模型,则需要hasMany
函数。
I refer to the Laravel docs for more information about this. 有关此的更多信息,请参阅Laravel文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.