且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Laravel 5根据ID获取名称

更新时间:2021-07-05 19:33:02

您可以使用雄辩的关系.您在问题中描述的是一个一对多关系,表示一个部门可以有许多用户,并且每个用户都属于一个部门.因此,您需要为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