繁体   English   中英

如何从laravel中的另一个数据库表中检索值?

[英]How to retrieve value from another database table in laravel?

我有两个名为usersprofiles表。在users表中有一个名为id的列,在profiles表中有一个名为userID的列。现在我希望当users表增加id然后userID分别自动填充。

如果有人创建配置文件,则userID列会根据登录usersid自动填充。我该怎么做?

用户模型:

class User extends Authenticatable
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $table ="users";
    protected $fillable = [
        'userName', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function profileHave(){
        return $this->hasOne('App\Profile','userID');
    }
}

型材型号:

class Profile extends Model
{
    //
    protected $table = "profiles";
    public $fillable = ["userID","firstName","lastName","middleName","DOB","gender","featuredProfile","email","phone","summary","profilePic"];

    public function userHave(){
        return $this->belongsTo('App\User','userID');
   }
}

但是当我添加一个带有用户的配置文件时,在profiles表中userID列是空白的。但它应该根据users表的登录 ID 填写。

顺便说一下,我是 Laravel 的新手。 谢谢。

像这样获取用户ID

$id = Auth::id();

然后将此值分配给配置文件中的用户属性,例如

$profile->userID = $id

保存配置文件时,向其中添加用户:

$profile->userHave = $user

几件事:

  • 您的Profile模型不需要userID即可填写。 这是由您的关系填充的,因此真的不应该填充。

  • 这种关系的命名有点奇怪。 它实际上应该是您希望用于获取关系的属性的名称。 例如,我会将您个人资料中的用户关系称为user

     public function user() { return $this->belongsTo('App\\User','userID'); }

    有了这个,您将使用以下内容将用户添加到配置文件中:

     $profile->user = $user;
  • 最后,考虑一下您是否真的需要配置文件模型

    您的配置文件模型中的所有属性都是用户的属性。 如果您计划为每个用户拥有一个配置文件,则没有理由为配置文件使用不同的模型。

暂无
暂无

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

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