【发布时间】:2021-07-22 03:33:19
【问题描述】:
我需要创建一个查询,从帖子数组中获取所有标签。在标签和帖子之间的多对多多态关系中
标签模型
class Tag extends Model
{
use HasFactory;
protected $guarded = ['id'];
//
public function posts()
{
return $this->morphedByMany(Post::class, 'taggable');
}
}
后模型
类 Post 扩展模型 { 使用 HasFactory;
protected $guarded = ['id'];
public function tags()
{
return $this->morphToMany(Tag::class, 'taggable');
}
}
标签迁移
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
可标记迁移
public function up()
{
Schema::create('taggables', function (Blueprint $table) {
$table->id();
$table->bigInteger('tag_id')->unsigned();
$table->morphs('taggable');
$table->foreign('tag_id')->references('id')->on('tags')
->onDelete('cascade')
->onUpdate('cascade');
});
}
迁移后
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('description');
// 1 borrador, 2 revision, 3 publicado, 4 caducado
$table->enum('status', [Post::BORRADOR, Post::REVISION, Post::PUBLICADO, Post::CADUCADO]);
// Para diferenciar entre publicaciones del Sistema (Admin = 1) o de usuarios normales (USERS = 2)
$table->enum('type', [Post::ADMIN, Post::USERS]);
$table->boolean('atemporal');
$table->string('slug')->unique();
$table->unsignedBigInteger('user_id')->nullable();
$table->unsignedBigInteger('survey_id')->nullable();
$table->foreign('user_id')->references('id')->on('users')->onDelete('set null');
$table->foreign('survey_id')->references('id')->on('surveys');
$table->timestamps();
});
类别迁移
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->unsignedBigInteger('parent_id')->nullable();
$table->string('slug');
$table->foreign('parent_id')->references('id')->on('categories')->onDelete('cascade');
$table->timestamps();
});
数据透视表 CATEGORY_POST
Schema::create('category_post', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('category_id');
$table->unsignedBigInteger('post_id');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->timestamps();
});
关系帖子
public function categories()
{
return $this->belongsToMany(Category::class);
}
关系类别
public function posts()
{
return $this->belongsToMany(Post::class);
}
我已经尝试过了,但我无法让它工作
$posts = Post::whereHas('categories', function($query) {
$query->whereIn('category_id', [$this->categoriaTags]);
})->get();
// Here I get the list of posts from which I want to get their tags, this is OK.
//But then I can't get the right query to get the tags.
$tags = Tag::whereHasMorph('posts', function($query) use($posts){
$query->where('tag_id', $posts);
})->get();
有什么建议吗?谢谢
【问题讨论】:
标签: laravel