[英]Laravel belongsTo Relationship
Ok, I am a little confused with the belongsTo relationship for Models. 好吧,我对模特的belongsTo关系有点困惑。
I have a Feeds model that extends Eloguent. 我有一个扩展Eloguent的Feeds模型。
I have created a relationship function called User. 我创建了一个名为User的关系函数。
public function user(){
return $this->belongsTo('User'); // and I also tried return $this->belongsTo('User', 'user_id');
}
On the view I am trying to do : 在我想要做的观点上:
@foreach($feeds as $feed)
{{$feed->user()->first_name}} {{$feed->user()->last_name}}
@endforeach
but I am getting this error Undefined property: Illuminate\\Database\\Eloquent\\Relations\\BelongsTo::$last_name 但我收到此错误未定义属性:Illuminate \\ Database \\ Eloquent \\ Relations \\ BelongsTo :: $ last_name
When I do $feed->user->first_name it works fine, but I thought user()->first_name was more efficient. 当我执行$ feed-> user-> first_name时它工作正常,但我认为user() - > first_name更有效。 What am I doing wrong?
我究竟做错了什么?
This are the fields and data types of the database: 这是数据库的字段和数据类型:
feeds 供稿
feed_id INT
user_id INT
feed Text
created_at TIMESTAMP
updated_at TIMSTAMP
school_id INT
users 用户
user_id INT
username VARCHAR
password VARCHAR
first_name VARCHAR
last_name VARCHAR
created_at TIMESTAMP
updated_at TIMESTAMP
Use the dynamic property 使用动态属性
$feed->user->first_name;
When you use the dynamic property it is the same as doing the below except Laravel does it for you using the magic __call()
method. 当您使用动态属性时,它与执行以下操作相同,除非Laravel使用magic
__call()
方法为您执行此操作。
$feed->user()->first()->first_name;
using just the function $feed->user() allows you to get the relationship which allows you to add extra constraints and with
relations before fetching the entity on the other end. 只使用功能$馈>用户()可以让你得到它允许你添加额外的约束和关系,
with
获取在另一端的实体之前的关系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.