亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Laravel 雄辯 多對多通過其他表與名稱代替 id 并獲取其他數據

Laravel 雄辯 多對多通過其他表與名稱代替 id 并獲取其他數據

PHP
飲歌長嘯 2022-08-05 18:44:52
我有兩個主要表,帖子和類別,它們應該具有多對多關系。我知道你可以用一個名為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對象作為關系,而只是作為一個普通的查詢結果。
查看完整描述

1 回答

?
森欄

TA貢獻1810條經驗 獲得超5個贊

我認為您的第二個查詢已經解決了您的問題。只需像這樣對它進行一些修改即可。


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

 }


查看完整回答
反對 回復 2022-08-05
  • 1 回答
  • 0 關注
  • 131 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號