Laravel中的hasOne关系不起作用?

时间:2015-02-03 16:39:55

标签: php laravel-4 eloquent

我有一对一的关系,我想在 laravel 工作。

我正在尝试使用useralert表。

Use r表的主键为id,其中的另一个ID称为id_custom。 在Alerts表中,我将id_custom作为主键。

以下是用户模型中的关系:

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

这是警报模型:

class Alerts extends Eloquent
{

    /**
     *
     *
     * The database table used by the model.
     *
     *
     *
     * @var string
     *
     */
    protected $table = 'alerts';
    protected $primaryKey = 'id_custom';

    /**
     *
     *
     * The attributes excluded from the model's JSON form.
     *
     *
     *
     * @var array
     *
     */
    protected $hidden = array();
    public $timestamps = false;
}

在视图中我尝试Auth::user()->alerts->profit(其中profitAlerts表中的一列。

我做错了什么?

1 个答案:

答案 0 :(得分:6)

您的hasOne方法目前正在user_id表格中查找alerts。您需要显式设置您要查找的外键和本地键。

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');
}
相关问题