php - 从数据透视表中检索数据

标签 php mysql laravel laravel-5 eloquent

我浏览过一些类似的主题,但没有找到可行的解决方案。主要是我不太理解这个概念。 我有一个具有以下结构的简单数据库:

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/

相关文章:

php - 如何在 laravel 5 中将公用文件夹更改为 public_html

php - 如何从 Laravel belongsToMany 关系中获取行?

MySQL 8.0 - 客户端不支持服务器请求的身份验证协议(protocol);考虑升级MySQL客户端

mysql - 计算时间戳在 X 间隔内的 mysql 数据库中的行

php - 如何在 Docker 容器中安装 PHP Composer

php - MySql 逻辑顺序

javascript - android 登录页面无法获取 php 响应

php - 使用 SQL 获取矩形(或平面 2D map )内的 GPS 坐标

mysql - 如何检查表中是否存在多对多对多...

php - Laravel 和 Blade 的 undefined variable