如何使用 Eloquent 获取具有外键的另一列的值

How do I get the value of another column with a foreign key usingEloquent

我有两个table

Users
    -ID
    -Company
    -Name

Companies
    -ID
    -company_name

Company 列填充了来自 Company table 的公司 ID 如此如此

用户

----------------------
|ID | Name | Company |
----------------------
| 1 | Bob  | 1       |
| 2 | Mary | 1       |
| 3 | Sue  | 2       |


Comapnies
-------------------
|ID | company_name| 
-------------------
| 1 | Google      |
| 2 | Microsoft   |

如何通过公司ID的外键引用Name?

我的用户模型

public function company() {
        return $this->hasOne('Company');
    }

公司模式

   public function company() {
        return $this->belongsTo('User');
    }

如果我做

$users = User::find(1);

我得到了公司的ID,但我需要得到名称。

我试过了

 foreach ($users->company as $company){
        echo $company->company_name;
}

$users->company->company_name;

这只会导致 Trying to get 属性 of non-object

foreach ($users->company as $company)
    {
        echo $company->pivot->comapny_name;
    }

这只是说 Invalid argument supplied for foreach()

我不知道该怎么做。

我认为你需要像这样放置你的关系声明:

public function company() {
    return $this->hasOne('Company', 'Company');
}

Laravelrelationships docs这样说

Take note that Eloquent assumes the foreign key of the relationship based on the model name. In this case, Phone model is assumed to use a user_id foreign key. If you wish to override this convention, you may pass a second argument to the hasOne method. Furthermore, you may pass a third argument to the method to specify which local column that should be used for the association

您的关系定义不正确。在您的代码中,您尝试将 User 定义为父级,将 Company 定义为子级。但是,您的 table 设置为公司是父级,用户是子级。基本上,包含外键的 table(用户 table 有公司的外键)应该在 belongsTo 端。

因此,需要将用户 hasOne company and company belongsTo 用户切换为 company hasOne user and user belongsTo company。

除此之外,您的外键与 Laravel 默认使用的命名约定不匹配,因此您需要在关系定义中指定外键。

用户:

public function company() {
    return $this->belongsTo('Company', 'Company');
}

公司:

public function user() {
    return $this->hasOne('User', 'Company');
}

正确设置关系后,您将能够:

$user = User::find(1);
var_export($user->company->company_name);