다음 테이블이 있습니다.
사용 테이블 :
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('firstname');
$table->string('surename');
$table->string('address')->nullable();
$table->string('city')->nullable();
$table->string('country')->nullable();
$table->string('postcode')->nullable();
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->string('facebook_id')->nullable();
$table->string('linkedin_id')->nullable();
$table->string('twitter_id')->nullable();
$table->timestamps();
});
설정 테이블 :
Schema::create('settings', function (Blueprint $table) {
$table->increments('id');
$table->string('value');
$table->timestamps();
});
Setting_user (피벗 테이블) :
Schema::create('setting_user', function (Blueprint $table) {
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->integer('setting_id')->unsigned();
$table->foreign('setting_id')->references('id')->on('settings');
$table->timestamps();
});
카테고리 표 :
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Setting_category (피벗 테이블) :
Schema::create('setting_category', function (Blueprint $table) {
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories');
$table->integer('setting_id')->unsigned();
$table->foreign('setting_id')->references('id')->on('settings');
$table->timestamps();
});
내 사용자 모델에서 이것은 belongsToMany 관계를 가지고 있습니다.
public function settings()
{
return $this->belongsToMany(Setting::class, 'setting_user', 'user_id','setting_id')->with('category');
}
그리고 내 설정 모델에서 :
보호 된 $ table = '설정';
public function category()
{
return $this->hasMany(Categories::class,'id');
}
이렇게 액세스하면 :
public function settings()
{
$user = User::find(1);
return $user->settings()->with('category')->first();
}
이것이 내가 얻는 결과입니다.
{"id":1,"value":"87658675.jpg","created_at":"2017-07-04 00:00:00","updated_at":null,"pivot":{"user_id":1,"setting_id":1},"category":[{"id":1,"name":"avatar","created_at":"2017-07-06 00:00:00","updated_at":null}]}
category-> id == 1 인 설정 만 가져올 수있는 방법은 무엇입니까?
많은 감사
지정된 사용자 및 지정된 범주에 대한 설정 만 가져 오려면 whereHas()
다음을 사용하십시오 .
public function settings()
{
$categoryId = 1;
$userId = 1;
return Settings::whereHas('categories', function ($q) use ($categoryId) {
$q->where('id', $categoryId);
})
->whereHas('users', function ($q) use ($userId) {
$q->where('id', $userId);
})
->get();
}
이 작업을 수행하려면 관계를 수정하십시오. 모든 관계처럼 보인다는해야 belongsToMany()
하지hasMany()
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다