【发布时间】:2014-09-21 10:46:26
【问题描述】:
我有一个User 模型和一个Organization 模型,我试图将它们相互关联。
users 表有 id 和 current_organization_id(外键)字段(在其他普通字段中)。
organizations 表具有 id 和 owner_id(外键)字段(以及一些其他数据字段)。
还有一个数据透视表organization_user,通过它们各自的id 将两者联系起来。
我的模型是这样设置的:
用户:
<?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');
}
}
组织:
<?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');
}
}
这个想法是单个组织归一个用户所有,但一个组织有很多用户,每个用户都有一个“当前”组织,他们可以从他们所属的任何组织中选择。
我遇到的问题是,当我尝试执行$user->current_organization->id 时,我得到一个Trying to get property of non-object 错误,如果我尝试$user->current_organization()->id;,我得到一个Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$id 错误。
关于我做错了什么的任何想法,我无法像我在上面尝试做的那样检索current_organization?
编辑:
我认为这与我的 hasOne 关系有关,但我尝试这样做:
public function current_organization()
{
return $this->hasOne('Organization', 'id', 'current_organization_id');
}
还是什么都没有。 $user->current_organization; 正在返回 NULL。
【问题讨论】:
标签: php laravel laravel-4 eloquent