簡體   English   中英

從數據透視表中檢索數據

[英]retrieve data from pivot table

我經歷了一些類似的主題,但沒有找到可行的解決方案。 主要是我沒有很好地理解這個概念。 我有一個具有以下結構的簡單數據庫:

QUESTIONS
qid
question

TAGS
tagid
tag name

QUESTION_TAGS
qid
tagid

我的問題模型:

class Question extends Model
{
    protected $table="questions";

    public function tags()
    {
        return $this->hasMany('App\Question_tags','qid','qid');
    }

}

我的標簽模型:

class Tags extends Model
{
    protected $table="tags";
}

Question_tags 模型:

class Question_tags extends Model
{
    protected $table="question_tags";
}

問題控制器:

class QuestionCtrl extends Controller
{

    public function getquesdet(){
        $id = Request::input('id');

        $question = Question::where('q_id','=',$id)->with('tags')
        ->get();

        return $question;      
  }
 };

正如預期的那樣,返回的值由ids組成。 所以,我希望返回的值是tag names 我很樂意聽到一些解釋。

通過查看您的數據庫模式,它是一個many-to-many關系,因此您的關系函數應為:

Question模型中:

public function tags()
{
    return $this-> belongsToMany('App\Tags', 'QUESTION_TAGS', 'qid', 'tagid');
}

Tags模型中:

public function questions()
{
    return $this-> belongsToMany('App\Question', 'QUESTION_TAGS', 'tagid', 'qid');
}

然后在你的控制器中,你可以寫成:

$question = Question::where('q_id','=',$id)->with('tags')->first();

return $question->tags->pluck('name'); // returns array of tag names

注 - 無需為數據透視表Question_tags定義模型。

你好,在你的例子中,你試圖在問題和標簽之間建立多對多的關系,你的數據庫看起來不錯。 但是在您的模型中,您已經創建了關系函數來填充相關數據,從而解決該函數中的問題。 你的問題模型是

class Question extends Model
{
protected $table="questions";

public function tags()
{
    return $this->hasMany('App\Question_tags','qid','qid');
}

}

在此您使用hasMany函數,該函數用於建立 1 對多的關系。

使用函數belongsToMany使關系成為多對多。

我也面臨這樣的問題。 我需要根據標記模型的標記ID提出所有問題。 請讓我知道

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM