Laravel 雄辩 多对多通过其他表与名称代替 id 并获取其他数据

我有两个主要表,帖子和类别,它们应该具有多对多关系。我知道你可以用一个名为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对象作为关系,而只是作为一个普通的查询结果。



饮歌长啸
浏览 117回答 1
1回答

森栏

我认为您的第二个查询已经解决了您的问题。只需像这样对它进行一些修改即可。public function posts(){    return PostQuestionCategory::with('question.post')->where('category_name', $this->name)->get();}只需将帖子与问题一起添加即可将其包含在返回的集合中。或者,如果您也与类别有关系,那么您只需添加类别关系,就像这个一样 public function posts() {        return PostQuestionCategory::with('question.post', 'category')->where('category_name', $this->name)->get(); }
打开App,查看更多内容
随时随地看视频慕课网APP