Sip*_*per 16 php mysql laravel laravel-5
我有两个表,看起来(迁移):
Schema::create('sets', function(Blueprint $table)
{
$table->increments('id');
$table->string('key');
$table->string('name');
$table->string('set_type');
$table->integer('belongs_to')->unsigned();
$table->timestamps();
$table->foreign('belongs_to')->references('id')->on('sets')->onDelete('cascade');
});
Schema::create('posts', function(Blueprint $table)
{
$table->bigIncrements('id');
$table->bigInteger('user_id')->unsigned();
$table->bigInteger('set_id')->unsigned();
$table->string('post_type', 25);
$table->text('post');
$table->boolean('is_reported')->default(false);
$table->boolean('is_hidden')->default(false);
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('set_id')->references('id')->on('sets');
});
Run Code Online (Sandbox Code Playgroud)
'set'表用于存储应该查看帖子的位置(国家,城市......)的数据.例如,让我们存储一些国家:
id | key | name | belongs_to
1 | europe | Europe | null
2 | germany-all | Germany | 1
3 | germany-berlin | Berlin | 2
4 | germany-frankfurt | Frankfurt | 2
5 | poland-all | Poland | 1
6 | poland-warsaw | Warsaw | 5
7 | england-all | England | 1
Run Code Online (Sandbox Code Playgroud)
并且,我的帖子set_id为6.从逻辑上看,当我想要从欧洲获得帖子(ID 1)时,该帖子也应该被返回,因为6属于5,而5属于1.这就是我想要的去做.可以不使用过多的PHP吗?
好的,我找到了最好的解决方案.这是嵌套集模式.我使用了baum包,看起来:
对于sets表格我添加了Baum的colums:
Schema::create('sets', function(Blueprint $table) {
$table->bigIncrements('id');
$table->integer('parent_id')->nullable()->index();
$table->integer('lft')->nullable()->index();
$table->integer('rgt')->nullable()->index();
$table->integer('depth')->nullable();
$table->string('key');
$table->string('name');
$table->string('set_type');
$table->timestamps();
});
Run Code Online (Sandbox Code Playgroud)
并做了!只需获取set_id并返回帖子,例如:
$sets = Set::where('key', '=', $myKey)->first()->getDescendantsAndSelf()->lists('id');
$posts = Post::whereIn('set_id', $sets)->with(['user'])->take(6)->get();
Run Code Online (Sandbox Code Playgroud)
我留下这个给后代;)
| 归档时间: |
|
| 查看次数: |
639 次 |
| 最近记录: |