저는 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)과 같은 작업을하려고하면 피벗 테이블 내에 적절한 행이 추가되므로 관계가 있음을 알 수 있습니다.
왜 쿼리가 작동하지 않는 것 같아요?
정말 고맙습니다. 감사합니다. 나는 그것이 단순 할 것이라고 알고있었습니다. –