本文介绍了Laravel属于关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个扩展Eloguent的Feeds模式。



我创建了一个名为User的关系函数。

  public function user(){
return $这 - >属于关联( '用户'); (我也尝试返回$ this-> belongsTo('User','user_id');
}

在我想要做的事情上:

  @foreach($ feeds as $ feed)
{{$ feed-> user() - > first_name}} {{$ feed-> user() - > last_name}}
@endforeach

但我收到此错误Undefined属性:Illuminate\Database\Eloquent\Relations\BelongsTo :: $ last_name



当我做$ feed-> user-> first_name它工作正常,但我认为user() - > first_name更有效率,我做错了什么?



这是数据库的字段和数据类型:



feed

  feed_id INT 
user_id INT
feed文本
created_at TIMESTAMP
updated_at TIMSTAMP
school_id INT

用户

  user_id INT 
username VARCHAR
密码VARCHAR
first_name VARCHAR
last_name VARCH AR
created_at TIMESTAMP
updated_at TIMESTAMP


解决方案

p>使用动态属性

  $ feed-> user-> first_name; 

当您使用动态属性时,与执行以下操作相同,除了Laravel为您使用魔术 __ call()方法。

  $ feed-> user() - > first() - > first_name; 

只需使用$ feed-> user()函数即可获得允许您在另一端提取实体之前,添加额外的约束和关系。


Ok, I am a little confused with the belongsTo relationship for Models.

I have a Feeds model that extends Eloguent.

I have created a relationship function called 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

When I do $feed->user->first_name it works fine, but I thought user()->first_name was more efficient. 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.

$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.

这篇关于Laravel属于关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 02:45