I have a User
model and an Organization
model which I'm trying to relate to one another.
The users
table has id
and current_organization_id
(foreign key) fields (among the other normal fields).
The organizations
table has id
and owner_id
(foreign key) fields (along with some other data fields).
There is also a pivot table, organization_user
which links the two via their respective id
.
My models are set up like this:
User:
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends \Cartalyst\Sentry\Users\Eloquent\User implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password', 'remember_token');
/**
* Defining many to many relationship to organizations
*/
public function organizations()
{
return $this->belongsToMany('Organization');
}
/**
* Defining relationship to current selected organization
*/
public function current_organization()
{
return $this->hasOne('Organization');
}
}
Organization:
<?php
class Organization extends \Eloquent {
// Add your validation rules here
public static $rules = [
// 'title' => 'required'
];
// Don't forget to fill this array
protected $fillable = [];
public function users()
{
return $this->hasMany('User');
}
public function owner()
{
return $this->belongsTo('User');
}
}
The idea is that a single organization is owned by a user, but an organization has many users, and each user has a "current" organization, which they can select from any organization that they belong to.
The problem I'm running into is that when I try to do $user->current_organization->id
I get a Trying to get property of non-object
error, and if I try $user->current_organization()->id;
I get a Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$id
error.
Any ideas on what I'm doing wrong that I can't retrieve the current_organization
like I'm trying to do above?
EDIT:
I'm thinking it has to do with my hasOne
relationship, but I tried doing this:
public function current_organization()
{
return $this->hasOne('Organization', 'id', 'current_organization_id');
}
and still nothing. $user->current_organization;
is returning NULL
.