I have a one to one relationship I am trying to get to work in laravel .
I have a user
and an alert
table I am trying to use.
Primarykey of Use
r table is id
and another id in there is called id_custom
. In the Alerts
table I have id_custom
as the primary key.
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.
What am I doing wrong?
Your hasOne
method is currently looking for user_id
in your alerts
table. 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
.
Then you could change the method in your User.php model to alert
and do:
public function alert()
{
return $this->hasOne('Alerts');
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.