[英]hasOne relationship in Laravel not working?
I have a one to one relationship I am trying to get to work in laravel . 我有一对一的关系,我想在laravel工作。
I have a user
and an alert
table I am trying to use. 我有一个user
和我想要使用的alert
表。
Primarykey of Use
r table is id
and another id in there is called id_custom
. Use
r表的主键是id
,其中的另一个id称为id_custom
。 In the Alerts
table I have id_custom
as the primary key. 在Alerts
表中,我将id_custom
作为主键。
Here is the relationship in the users model: 这是用户模型中的关系:
public function alerts()
{
return $this->hasOne('Alerts', 'id_custom');
}
Here is the alerts model: 这是警报模型:
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;
}
Than in a view I am trying to do Auth::user()->alerts->profit
(where profit
is a column in the Alerts
table. 在视图中我试图做Auth::user()->alerts->profit
(其中profit
是Alerts
表中的一列)。
What am I doing wrong? 我究竟做错了什么?
Your hasOne
method is currently looking for user_id
in your alerts
table. 您的hasOne
方法当前正在alerts
表中查找user_id
。 You need to explicitly set the foreign and local key you're looking for. 您需要显式设置要查找的外键和本地键。
return $this->hasOne('Model', 'foreign_key', 'local_key');
In your instance if would be 在你的实例中,如果是
return $this->hasOne('Alerts', 'id_custom', 'id');
You would make things much tidier for yourself if you changed the User
attribute id_custom
to alert_id
. 你会做很多的事情为自己整洁,如果你改变了User
属性id_custom
到alert_id
。
Then you could change the method in your User.php model to alert
and do: 然后,您可以更改User.php模型中的方法以发出alert
并执行以下操作:
public function alert()
{
return $this->hasOne('Alerts');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.