我有以下表格:獲取ID爲1的設置? Laravel5.4 *
用途表:
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');
}
在我的設置模式:
保護$表= 「設置」;
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}]}
如何我類別 - > id來獲取只有設置== 1 ?
非常感謝
謝謝你的提示。看到我的解決方案:) @Alexey Mezenin – Marco
我確實投了你的答案。但我不知道如何選擇最好的答案。我很高興爲你做到這一點:) – Marco