【问题标题】:How to retrieve value from another database table in laravel?如何从 laravel 中的另一个数据库表中检索值?
【发布时间】:2016-04-18 05:02:00
【问题描述】:

我有两个名为usersprofiles 的表。在users 表中有一个名为id 的列,在profiles 表中有一个名为userID 的列。现在我想要@987654327 @table增加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 的新手。 谢谢。

【问题讨论】:

    标签: php mysql sql-server laravel laravel-5.2


    【解决方案1】:

    这样获取用户ID

    $id = Auth::id();
    

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

    $profile->userID = $id
    

    【讨论】:

    • 我真的不明白我在哪里添加这些?
    • 当您将配置文件数据保存到数据库以在 laravel 中保存数据时,您必须创建一个配置文件对象,然后像这样填充它的所有属性 $profile = new Profile() $profile->firstName = 'test' $profile->lastName= 'test' $profile->userID = Auth::id(); $profile->save()
    • 它在我保存Class 'App\Http\Controllers\Auth' not found时显示
    • 你的 pastebin 链接向我显示 404 错误,要删除 auth not found 错误,请使用代码顶部的 Auth 类 nampspace `use \Auth'
    • 现在显示Attempt to assign property of non-object这个错误。
    【解决方案2】:

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

    $profile->userHave = $user
    

    有几点:

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

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

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

      这样,您可以使用以下内容将用户添加到个人资料中:

      $profile->user = $user;
      
    • 最后,考虑一下您是否真的需要个人资料模型

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

    【讨论】:

    • 我在哪里添加$profile->user = $user; 这个?在用户控制器中?
    • 视情况而定。您在哪里创建/保存您的个人资料?放在那里。
    • 您需要获取您想要添加配置文件的用户。 $user = User::find(1);
    猜你喜欢
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    • 2017-04-12
    • 2012-06-11
    • 2018-06-21
    • 2022-01-15
    • 1970-01-01
    • 2020-08-29
    相关资源
    最近更新 更多