I've two tables, looks that (migrations):

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');

});

The 'set' table is for storing data in which the location (country, city...) the post should be view. For example, let's store some countries:

   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

而且,我的帖子把_id设置为6,从逻辑上看,当我想从欧洲(ID 1)获取帖子时,那个帖子也应该返回,因为6属于5,5属于1.这就是我想要做的.有可能在不使用太多PHP的情况下做到这一点吗?

推荐答案

Okay, I found the best solution. It's the Nested Set pattern. I used baum package and it looks that:

对于sets个表,我添加了鲍姆柱:

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();
});

And done! Just get set_id's and return posts, for example:

$sets = Set::where('key', '=', $myKey)->first()->getDescendantsAndSelf()->lists('id');
$posts = Post::whereIn('set_id', $sets)->with(['user'])->take(6)->get();

我要把这个留给子孙后代;)

Laravel相关问答推荐

Laravel模型嵌入嵌套模型时只附加属性

laravel vue 惯性分页器删除上一个和下一个链接

如何在数据来自Rest API的flutter中创建下拉类别名称列表?

在 laravel 项目中放置 css 文件的位置

如何将用户对象绑定到中间件中的请求

laravel render() 方法有什么用?

Laravel 5.4 - 如何为同一个自定义验证规则使用多个错误消息

克隆后设置 Laravel 项目

查询构建器中的 Laravel 5 多重 Select ()

如何在 Eloquent 上设置条件关系

Laravel 5.3 Electron邮件队列中不允许序列化关闭

Laravel 在特定文件夹中创建迁移文件

扩展模型 == 扩展 Eloquent?

在 Laravel 中按用户名查找用户

Laravel Eloquent 查询生成器默认 Where 条件

Blade 中的条件扩展

在 laravel 中删除排队的作业(job)

[Vue 警告]:找不到元素:#app

Laravel 中的 isDirty() 是什么意思?

Laravel:如何在 PhpUnit 上启用堆栈跟踪错误