Laravel 5根据ID获取名称 [英] Laravel 5 get name based on ID

查看:429
本文介绍了Laravel 5根据ID获取名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户和部门表.所以我的Departments表可能会像这样

I have a users and departments table. So my departments table might have a row like so

 id | departmentName         
----------------------
 2  | Marketing       
----------------------

users表可能有类似的内容

And the users table might have something like

 id | name       | email                | departmentId           
-------------------------------------------------------
 18 | Nick       | nick@email.com       | 2   
-------------------------------------------------------

因此,用户表通过ID链接到部门表.

So the users table links to the departments table via the id.

现在,在索引函数中,进入我的UserController

So now onto my UserController, in the index function, I do

public function index()
{
    $users = User::all();
    return view('users.index', compact('users'));
}

现在,这将显示我的users表中的所有内容.

Now that will display everything within my users table.

我的问题是,我不想显示departmentId.我想显示链接到该DepartmentID的departmentName.因此,在上面的示例中,我的该行的用户索引页应显示Marketing,而不是2.

My problem is, I do not want to display the departmentId. I want to display the departmentName which is linked to that departmentID. So in the above example, my users index page for that one row should show Marketing, not 2.

我该怎么做?

谢谢

推荐答案

您可以使用雄辩的关系.您在问题中描述的是一个一对多关系,表示一个部门可以有许多用户,并且每个用户都属于一个部门.因此,您需要为departments表设置模型(如果尚未设置),然后在User模型中定义关系,如下所示:

You can use Eloquent Relationships. What you described in your question is a One-to-Many Relation, meaning a department can have many users, and each user belongs to a department. So you'll need to setup a model for your departments table (if you haven't done so already) and then define the relationship in your User model like so:

class User extends Model
{
    public function department()
    {
        return $this->belongsTo('App\Department', 'departmentId');
    }
}

然后您可以通过该关系访问视图中的部门详细信息:

You can then access the department details in your view via that relationship:

@foreach ($users as $user)
    {{ $user->department->departmentName }}
@endforeach

这篇关于Laravel 5根据ID获取名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆