简体   繁体   中英

How to retrieve value from another database table in laravel?

I have two table named users and profiles .In users table its have a column named id and in profiles table its have a column named userID .Now i want when users table increasing id then userID automatic fill up respectively.

If anyone create profile then the userID column auto fill up according to the login users table id .How can i do that?

User Model:

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');
    }
}

Profile Model:

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');
   }
}

But when i add a profile with an user then in profiles table userID column is blank.But it should be fill up according to login id of the users table.

By the way i am new in Laravel. Thanks.

Get the user id like this

$id = Auth::id();

and then assign this value to user property in profile like

$profile->userID = $id

When saving a profile, add a user to it with:

$profile->userHave = $user

A couple of things:

  • Your Profile model does not need userID to be fillable. This is filled by your relation so really shouldn't be fillable.

  • The relation is named a bit weirdly. It should really be the name of the attribute that you expect to use to fetch the relation. For instance, I would call the user relation in your profile just user :

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

    With this, you would add a user to a profile with the following:

     $profile->user = $user;
  • Lastly, think about whether you actually need a profile model .

    All the attributes in your profile model are attributes of the user. If you plan on having a profile for every user, you have no reason to have a different model for a profile.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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