我有两个主要表,帖子和类别,它们应该具有多对多关系。我知道你可以用一个名为category_post的表来做到这一点,但这不是我能够使用的结构的设置方式。
它是这样的:帖子与问题有一对一的关系,问题通过帖子有类别。
我的数据库如下所示:
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->text('contet');
}
Schema::create('post_questions', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('post_id');
$table->integer('views');
$table->integer('answers');
}
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->unique();
}
Schema::create('post_question_categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('post_question_id');
$table->string('category_name');
$table->string('additional_info');
}
如您所见,我的数据透视表既没有post_id也没有category_id而是一个post_question_id和一个在类别表中唯一的category_name。但是,应该的状态是具有帖子和类别的多对多。
问题还与查询additional_infos
这是我的模型:
class Post extends Model
{
public function question()
{
return $this->hasOne('App\PostQuestion')->with('categories');
}
}
class Question extends Model
{
public function post()
{
return $this->belongsTo('App\Post');
}
public function categories()
{
return $this->hasMany('App\PostQuestionCategory');
}
}
class PostQuestionCategory extends Model
{
public function question()
{
return $this->belongsTo('App\PostQuestion')->with('post');
}
}
class Category extends Model
{
public function posts()
{
}
}
所以这就是乐趣开始的地方:我想查询一个类别的所有帖子。我已经尝试过并通过3种方法获得:
1.
public function posts()
{
$name = $this->name;
return Post::whereHas('question', function ($question) use ($name) {
$question->whereHas('categories', function ($categories) use ($name) {
$categories->where('name', $name);
});
})->get();
}
第三个不是真正的选项,因为我不想操纵现有的数据库。在第二个中,我并没有真正将post对象作为关系,而只是作为一个普通的查询结果。
森栏