简体   繁体   English

Laravel一对一关系

[英]Laravel relationship with one-to-one

I have the following users table structure: 我有以下users表结构:

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

Now in my tbl_status : 现在在我的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. 现在,我想创建一个关系,如果在users表中的状态为1,我想获取其名称。 I have tried: 我努力了:

In my User model: 在我的User模型中:

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

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

In the Status model: Status模型中:

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. ...即使每个用户的默认状态为1,并且状态表的ID为1,但其值也始终为null

This relationship is backwards. 这种关系是倒退的。 Placing the status foreign key on the users table creates the following relationships: status外键放在users表上可创建以下关系:

  • User belongs to Status User属于Status
  • Status has many User s Status有很多User

However, the question shows a hasOne() relation on the User model for userstatuses() . 然而,问题示出了hasOne()的关系User对模型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 . 为此, tbl_status将需要一个user_id字段,但这意味着Status 只能属于一个 User

Instead, the correct relation for userstatus() on User should be belongsTo() : 相反, Useruserstatus()的正确关系应该是belongsTo()

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

Then we can use the proper relations on the User model: 然后,我们可以在User模型上使用适当的关系:

$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. 我认为最好的方法是添加一个user_id列,该列引用用户id列作为外键而不是状态。 That should fix it. 那应该解决它。

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

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