小编Jua*_*cón的帖子

laravel通过标签获取相关帖子

我想通过标签获取当前帖子的相关帖子,但老实说我无法获取。

我将向您展示我的表格结构。

帖子表:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->string('title');
        $table->string('slug')->unique();
        $table->text('body');
        $table->text('excerpt')->nullable();
        $table->string('stickers')->nullable();
        $table->integer('category_id')->nullable()->unsigned();
        $table->text('meta_description')->nullable();
        $table->text('meta_keywords')->nullable();
        $table->string('postimg')->nullable();
        $table->string('type')->nullable()->default('common');
        $table->boolean('published')->default(false);
        $table->softDeletes();
        $table->timestamps();
    });
}
Run Code Online (Sandbox Code Playgroud)

标签表:

public function up()
{
    Schema::create('tags', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name')->unique();
        $table->string('slug')->unique();
        $table->softDeletes();
        $table->timestamps();
    });
}
Run Code Online (Sandbox Code Playgroud)

我有一个数据透视表来处理帖子上的标签以及带有这些标签的帖子。

post_tag表:

public function up()
{
    Schema::create('post_tag', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('post_id')->unsigned();
        $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');

        $table->integer('tag_id')->unsigned();
        $table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
    });
}
Run Code Online (Sandbox Code Playgroud)

一切工作正常,一个标签有很多帖子,一个标签有很多标签,是多对多关系。

帖子模型:

public function tags()
{
    return $this->belongsToMany('App\Tag');
}
Run Code Online (Sandbox Code Playgroud)

标签型号:

public function posts()
{
  return $this->belongsToMany('App\Post'); …
Run Code Online (Sandbox Code Playgroud)

php tags laravel laravel-query-builder

0
推荐指数
1
解决办法
1891
查看次数

标签 统计

laravel ×1

laravel-query-builder ×1

php ×1

tags ×1