Laravel 中的 hasOne 关系不起作用?

hasOne relationship in Laravel not working?

我有一个一对一的关系,我想在 laravel.

工作

我有一个 user 和一个 alert table 我正在尝试使用。

User table 的主键是 id 并且其中的另一个 ID 称为 id_custom.

Alerts table 中,我将 id_custom 作为 主键

这是用户模型中的关系:

   public function alerts()
   {
       return $this->hasOne('Alerts', 'id_custom');
   }   

这是警报模型:

alerts->profit`(其中 `profit` 是 `Alerts` table 中的一列。 我究竟做错了什么?

您的 hasOne 方法当前正在您的 alerts table 中查找 user_id。您需要明确设置您要查找的外键和本地键。

return $this->hasOne('Model', 'foreign_key', 'local_key');

Source

在你的例子中如果是

return $this->hasOne('Alerts', 'id_custom', 'id');

如果将 User 属性 id_custom 更改为 alert_id

然后您可以将 User.php 模型中的方法更改为 alert 并执行:

public function alert()
{
    return $this->hasOne('Alerts');
}