【问题标题】:Laravel group user entities by categoriesLaravel 按类别对用户实体进行分组
【发布时间】:2018-05-23 02:51:40
【问题描述】:

我有三个表:用户、房间和房间类别。所以我想获得按类别分组的特定用户房间,但仅限于用户房间拥有的那些类别。这是我的模型和迁移:

房间模型

namespace App;

use Illuminate\Database\Eloquent\Model;

class Room extends Model
{
    protected $fillable = ['type_id', 'name', 'rooms_count', 'smoking'];

    // public $with = ['type'];

    public function user() 
    {
        return $this->belongsTo('App\User');
    }

    public function type() 
    {
        return $this->belongsTo('App\RoomType', 'type_id', 'id');
    }
}

房间类型模型

namespace App;

use Illuminate\Database\Eloquent\Model;

class RoomType extends Model
{
    protected $fillable = ['title'];

    public $with = ['rooms'];

    public function rooms()
    {
        return $this->hasMany('App\Room', 'type_id');
    }
}

用户模型

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function rooms() 
    {
        return $this->hasMany('App\Room');
    }
}

用户表迁移

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Rooms 表迁移

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateRoomsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('rooms', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_id');
            $table->unsignedInteger('type_id');
            $table->string('name');
            $table->integer('rooms_count');
            $table->boolean('smoking');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('rooms');
    }
}

房间类型迁移

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateRoomTypesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('room_types', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('room_types');
    }
}

所以我想得到这样的结果

[
  {
    "id": 1,
    "title": "Eum laboriosam.",
    "created_at": "2017-12-06 18:19:59",
    "updated_at": "2017-12-06 18:19:59",
    "rooms": [
      {
        "id": 1,
        "user_id": 1,
        "type_id": 1,
        "name": "room1",
        "rooms_count": 1,
        "smoking": 1,
        "created_at": "2017-12-06 18:53:39",
        "updated_at": "2017-12-06 18:53:39"
      }
    ]
  },
  {
    "id": 2,
    "title": "Atque officiis.",
    "created_at": "2017-12-06 18:19:59",
    "updated_at": "2017-12-06 18:19:59",
    "rooms": [
      {
        "id": 2,
        "user_id": 1,
        "type_id": 2,
        "name": "standart Delux",
        "rooms_count": 4,
        "smoking": 1,
        "created_at": "2017-12-06 19:15:49",
        "updated_at": "2017-12-06 19:15:49"
      },
      {
        "id": 3,
        "user_id": 1,
        "type_id": 2,
        "name": "standart Delux",
        "rooms_count": 4,
        "smoking": 1,
        "created_at": "2017-12-06 19:15:49",
        "updated_at": "2017-12-06 19:15:49"
      },
      {
        "id": 4,
        "user_id": 1,
        "type_id": 2,
        "name": "standart Delux",
        "rooms_count": 4,
        "smoking": 1,
        "created_at": "2017-12-06 19:15:49",
        "updated_at": "2017-12-06 19:15:49"
      },
      {
        "id": 5,
        "user_id": 1,
        "type_id": 2,
        "name": "standart Delux",
        "rooms_count": 4,
        "smoking": 1,
        "created_at": "2017-12-06 19:15:49",
        "updated_at": "2017-12-06 19:15:49"
      }
    ]
  }
]

我已经使用了这个代码:

return $roomsByCategories = RoomType::with('rooms')->get(); 

但我得到了我不需要的所有类别,因为用户只有 2 个类别的房间。

【问题讨论】:

  • 我也使用了 return $roomsByCategories = RoomType::with(['rooms' => function ($query) { $query->where('user_id', Auth::id()) ; }])->get();但仍然获得所有类别

标签: php mysql arrays laravel-5 collections


【解决方案1】:

你应该使用 where 条件并且可以像这样加入 room_types 和分组结果:

    return $roomsByCategories = User::with('rooms')
     ->join('room_types', 'room_types.id', '=', 'rooms.type_id')
     ->where('rooms.user_id', $user_id)
     ->groupBy('room_types.id')
     ->get(); 

或者你可以使用:

return $roomsByCategories = Rooms::with('type')
         ->where('rooms.user_id', $user_id)
         ->groupBy('room_types.id')
         ->get(); 

【讨论】:

  • 我不想只从 1 种类型获得房间。请查看有问题的我已经指定了我想要得到的结果
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-30
  • 1970-01-01
  • 1970-01-01
  • 2018-01-10
  • 1970-01-01
  • 1970-01-01
  • 2017-11-05
相关资源
最近更新 更多