我正在使用Laravel 4,我正在努力建立多对多的关系。这是我尝试做的一个例子。在这里,我试图在用户和组织之间建立一种多对多的关系。
这是我的迁移文件,创建了一个用户表、一个组织表和一个数据透视表来介于两者之间。
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('email');
$table->string('password');
$table->timestamps();
});
Schema::create('organizations', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('organization_user', function(Blueprint $table)
{
$table->increments('id');
$table->integer('organization_id')->unsigned()->index();
$table->foreign('organization_id')->references('id')->on('organizations')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
}
我还使用了默认的User模型,并添加了belongsToMany关系。
use Illuminate'Auth'UserTrait;
use Illuminate'Auth'UserInterface;
use Illuminate'Auth'Reminders'RemindableTrait;
use Illuminate'Auth'Reminders'RemindableInterface;
class User extends Eloquent 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');
public function organizations()
{
return $this->belongsToMany('Organization');
}
}
我创建了一个组织模型,这种关系朝着相反的方向发展。
class Organization extends 'Eloquent {
protected $fillable = ['name'];
public function users()
{
return $this->belongsToMany('User');
}
}
问题是,如果我尝试使用User::find(1)->organizations()进行查询,当然,在添加示例数据后,它总是以空数组的形式返回,而使用Organization::find(1)->users()也会朝相反的方向返回。奇怪的是,如果我尝试执行类似Organization::find(1)->users()->attach(1)的操作,它会在数据透视表中添加相应的行,这样它就知道存在关系。
关于为什么查询似乎不起作用,有什么想法吗?
这只是您访问关系的方式。尝试执行以下操作:
$organisations = User::find(1)->organisations;
$users = Organisation::find(1)->users;
如果使用关系的方法版本,也可以在查询中添加额外的内容。但是要小心,您需要在它后面加上get()
才能真正执行查询。
// The same as just accessing the property
$organisations = User::find(1)->organisations()->get();
// With extra clauses
$organisations = User::find(1)->organisations()->where('created_at', '>=', '2010-01-01 00:00:00')->get();