如何从 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填写。

顺便说一句,我是拉拉维尔的新人。谢谢。

像这样获取用户 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;
    
  • 最后,考虑一下你是否真的需要一个配置文件模型

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