简体   繁体   中英

Laravel relationship with one-to-one

I have the following users table structure:

id
email 
....
status // foreign key from tbl_status

Now in my tbl_status :

id
name
description

Now I would like to create a relationship such that if I have a status of 1 in the users table I would like to get its name. I have tried:

In my User model:

class User extends Model 
{
    protected $fillable = [
        'name', 'email', 'password', 'status'
    ];

    public function userstatus()
    {
        return $this->hasOne('App\Status', 'id', 'status');
    }
}

In the Status model:

class Status extends Model
{
    protected $fillable = [
        'name', 'description'
    ];
}

When fetching records via...

return User::with("userstatus")->paginate(10);

...it always returns the status as null even though each user has a default status of 1 and the status table has an ID of 1 with a value.

This relationship is backwards. Placing the status foreign key on the users table creates the following relationships:

  • User belongs to Status
  • Status has many User s

However, the question shows a hasOne() relation on the User model for userstatuses() . For this to work, tbl_status will need a user_id field, but this means that a Status can only belong to one User .

Instead, the correct relation for userstatus() on User should be belongsTo() :

public function userstatus() 
{
    return $this->belongsTo(App\Status::class, 'status'); 
}

Then we can use the proper relations on the User model:

$user = User::with('userstatus')->find(1); 
$user->status;                 // 1  (foreign key ID)
$user->userstatus->name;       // "status name"
$user->userstatus->description // "This is the status description."

I think the best way to do it will be to add a user_id column that references the users id column as the foreign key instead of status. That should fix it.

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