简体   繁体   中英

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:

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 . so, I want the returned value to be the 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:

In Question model:

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

In Tags model:

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 .

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.

Use the function belongsToMany to make the relation many to many.

I am also facing such a problem. I need all questions according to the tagid from tag model. please let me know that

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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