Laravel 4 belongsToMany关系退货清空
问题描述:
我正在使用Laravel 4,并且我正在努力建立多对多的关系。这是我想要做的一个例子。在这里,我试图建立用户和组织之间的多对多关系。Laravel 4 belongsToMany关系退货清空
这是我的迁移文件,创建一个用户表,一个组织表和一个数据透视表以在两者之间移动。
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();
});
}
我也使用了默认的用户模型,并添加了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');
}
}
的问题是,如果我尝试使用做一个查询用户::发现(1) - >组织(),当然在样本数据相加后,它总是返回一个空数组,同使用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();
太棒了,谢谢!我知道这会很简单。 – 2014-09-29 01:49:22