我浏览过一些类似的主题,但没有找到可行的解决方案。主要是我不太理解这个概念。 我有一个具有以下结构的简单数据库:
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";
}
问题 Controller :
class QuestionCtrl extends Controller
{
public function getquesdet(){
$id = Request::input('id');
$question = Question::where('q_id','=',$id)->with('tags')
->get();
return $question;
}
};
正如预期的那样,返回值由 ids
组成。所以,我希望返回值是标签名称
。我很乐意听到一些解释。
最佳答案
通过查看您的数据库模式,它是一个 many-to-many
关系所以你的关系函数应该是:
在问题
模型中:
public function tags()
{
return $this-> belongsToMany('App\Tags', 'QUESTION_TAGS', 'qid', 'tagid');
}
在标签
模型中:
public function questions()
{
return $this-> belongsToMany('App\Question', 'QUESTION_TAGS', 'tagid', 'qid');
}
然后在你的 Controller 中,你可以这样写:
$question = Question::where('q_id','=',$id)->with('tags')->first();
return $question->tags->pluck('name'); // returns array of tag names
注意 - 无需为数据透视表 Question_tags
定义模型。
关于php - 从数据透视表中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41119323/