简体   繁体   English

如何在Laravel中通过外键检索数据?

[英]How to retrieve data through Foreign Key in Laravel?

How to retrieve data in Laravel. 如何在Laravel中检索数据。

I am having table user in which I m having field parent_id in which I m showing information of its user_id. 我有一个表用户,其中我有一个字段parent_id ,其中我正在显示其user_id的信息

Now I want to show information of logged user 现在我想显示登录用户的信息

I tried this 我试过了

 {{Auth::user()->parent_id}}

I get the selected parent_id, now I want the name of that user_id. 我得到了选定的parent_id,现在我想要该user_id的名称。

I'm trying this 我正在尝试

{{(Auth::user()->parent_id)->value('name')}}

Its getting an error. 它得到一个错误。 Please tell me how can I write this in my code to get name of that parent id. 请告诉我如何在我的代码中编写此代码以获得该父ID的名称。

Define the relationship to the parent user in the User modal. 在“ User模式中定义与父用户的关系。

User Modal 用户模态

public function parent()
{
    return $this->belongsTo(User::class, 'parent_id');
}

blade

{{ Auth::user()->parent->name }}

There are (at least) two ways to do that. 有(至少)两种方法可以做到这一点。

1- Without relationship: you can select/find the user by parent_id and get its name. 1-没有关系:您可以通过parent_id选择/查找用户并获取其名称。 Something like this: 像这样:

{{ App\User::find(Auth::user()->parent_id)->name }}

2- With relation: and I think it is easier. 2-关系:我认为这更容易。 Define the relationship and set the parent_id as foreign key. 定义关系并将parent_id设置为外键。 Then you can get the parent user. 然后,您可以获取父用户。 Something like this: 像这样:

{{ Auth::user()->parentUser->name }} // parentUser is the method created in User model 

To define and use the relationship see the @Tharaka Dilshan answer. 要定义和使用这种关系,请参见@Tharaka Dilshan答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM