Laravel通过数据透视表拥有一个

编程入门 行业动态 更新时间:2024-10-07 12:23:07
本文介绍了Laravel通过数据透视表拥有一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

所以我有2个模型,用户&配置文件,关系设置如下:

So I have 2 models, User & Profile, the relationship is set up as follows:

/** * User belongs to many Profile * * @return \Illuminate\Database\Eloquent\Relations\belongsToMany */ public function profiles() { return $this->belongsToMany('App\Models\Profile', 'user_profiles'); }

我有3个表格,用户,个人资料& user_profiles(数据透视表)

I have 3 tables, users, profiles & user_profiles (the pivot table)

我的用户表中有一列称为active_profile,其中填充了配置文件ID.

I have a column in my users table called active_profile which gets populated with a profile id.

如何建立关系,以便可以调用类似以下的内容:

How can I set up the relationship so that I can call something like the following:

$user->active_profile

这样它将返回在active_profile中设置的ID的所有配置文件信息?

So that it will return all the profile information for the id set in active_profile?

推荐答案

您可以像这样将方法添加到您的User模型中:

You can add a method into your User model like this :

public function active_profile () { return $this->profiles() ->find($this->active_profile); }

然后可以将该方法调用为$ user-> active_profile();

and then you can call the method as $user->active_profile();

更多推荐

Laravel通过数据透视表拥有一个

本文发布于:2023-07-09 10:08:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1085533.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:透视   数据   Laravel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!