【问题标题】:hasOne relationship in Laravel not working?Laravel 中的 hasOne 关系不起作用?
【发布时间】:2015-04-02 22:57:05
【问题描述】:

我有一对一的关系,我正试图在 laravel 中工作。

我正在尝试使用user 和alert 表。

User 表的主键是id,其中的另一个 id 称为id_custom。

在Alerts 表中,我将id_custom 作为主键。

这是用户模型中的关系:

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

这是警报模型:

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

【问题讨论】:

  • 你试过return $this->hasOne(Alerts', 'id_custom', 'id')吗?

标签: php laravel-4 eloquent


【解决方案1】:

您的hasOne 方法当前正在您的alerts 表中查找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');
}

【讨论】:

    猜你喜欢
    • 2020-04-20
    • 2017-01-24
    • 2020-10-06
    • 1970-01-01
    • 2018-01-11
    • 2018-05-29
    • 2017-04-21
    • 2016-03-17
    • 1970-01-01
    相关资源
    最近更新 更多