简体   繁体   English

从数据透视表中检索数据

[英]retrieve data from pivot table

I have gone through some similar topics but did not find the working solution.我经历了一些类似的主题,但没有找到可行的解决方案。 Mostly I did not understand the concept well.主要是我没有很好地理解这个概念。 I have a simple database with the following structure:我有一个具有以下结构的简单数据库:

QUESTIONS
qid
question

TAGS
tagid
tag name

QUESTION_TAGS
qid
tagid

My Question model:我的问题模型:

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

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

}

my Tags model:我的标签模型:

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

Question_tags model: Question_tags 模型:

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

Question controller:问题控制器:

class QuestionCtrl extends Controller
{

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

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

        return $question;      
  }
 };

as expected, the returned value consists of ids .正如预期的那样,返回的值由ids组成。 so, I want the returned value to be the tag names .所以,我希望返回的值是tag names I would be happy to hear some explanation.我很乐意听到一些解释。

By looking your DB schemas it's a many-to-many relation so your relationship function should be as:通过查看您的数据库模式,它是一个many-to-many关系,因此您的关系函数应为:

In Question model:Question模型中:

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

In Tags model:Tags模型中:

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

Then in your controller, you can write as:然后在你的控制器中,你可以写成:

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

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

Note - There is no need to define a model for pivot table Question_tags .注 - 无需为数据透视表Question_tags定义模型。

hello in you example you are trying to make a many to many relation between questions and tags and your database looks good.你好,在你的例子中,你试图在问题和标签之间建立多对多的关系,你的数据库看起来不错。 but in your models you have made relational function to populate related data the problem in that functions.但是在您的模型中,您已经创建了关系函数来填充相关数据,从而解决该函数中的问题。 your question model is你的问题模型是

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

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

}

in this you are using hasMany function that is used to make the relation of 1 to many.在此您使用hasMany函数,该函数用于建立 1 对多的关系。

Use the function belongsToMany to make the relation many to many.使用函数belongsToMany使关系成为多对多。

I am also facing such a problem. 我也面临这样的问题。 I need all questions according to the tagid from tag model. 我需要根据标记模型的标记ID提出所有问题。 please let me know that 请让我知道

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM