【发布时间】:2015-03-18 22:58:09
【问题描述】:
我有以下表格:
用户
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('username', 30);
$table->string('email')->unique();
$table->string('password', 60);
$table->string('remember_token')->nullable();
$table->timestamps();
});
组织
Schema::create('organisations', function(Blueprint $table)
{
$table->increments('id');
$table->string('name')->unique('name');
$table->integer('owner_id')->unsigned()->index()->nullable();
$table->foreign('owner_id')->references('id')->on('users');
$table->timestamps();
});
这是我的 organisation_user 数据透视表:
public function up()
{
Schema::create('organisation_user', function(Blueprint $table)
{
$table->increments('id');
$table->integer('organisation_id')->unsigned()->index();
$table->foreign('organisation_id')->references('id')->on('organisations')->onDelete('cascade');
$table->integer('staff_id')->unsigned()->index();
$table->foreign('staff_id')->references('id')->on('users')->onDelete('cascade');
});
}
我的模型的规则是:
- 一个组织属于一个用户(所有者) - 并非总是如此,即
nullableowner_id - 一个组织下可能有很多用户(员工)
因此,我的Organisation eloquent 模型看起来像这样:
class Organisation extends Eloquent {
/**
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function owner()
{
return $this->belongsTo('User', 'owner_id', 'id');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function staffs()
{
return $this->hasMany('User', 'staff_id', 'id');
}
}
这就是我在控制器中加载模型并将其传递给视图的方式:
public function index()
{
return View::make('organisations.index')
->with('organisations', Organisation::with('owner', 'staffs')->get());
}
在我看来,我这样显示数据:
@foreach($organisations as $organisation)
<div>
Name : {{ $organisation->name }}
<br>
Owner: {{ $organisation->owner->email }}
<br>
Staffs: {{ $organisation->staffs->count() }}
</div>
@endofreach
执行上述操作时,出现以下错误:
SQLSTATE[42S22]: 找不到列: 1054 未知列 'where 子句'中的'users.staff_id' (SQL: select * from users where users.staff_id in (1))
知道为什么我在这里做错了吗?您如何正确地将关系与预加载联系起来?
我需要一个单独的数据透视表模型才能工作吗?
【问题讨论】:
标签: laravel laravel-4 relational-database eloquent eager-loading