繁体   English   中英

如何在laravel 5.2中获取两个表的数据

[英]how to get data for two tables in laravel 5.2

我在与Laravel合作时陷入了困境。 我有以下表格:学生表格和关系表格学生表格具有以下列ID,名称,性别,年龄和类别

关系表具有以下列id,id_student_girl,id_student_boy和状态

我需要显示如下输出:name_student_girl,name_student_boy和status

我试过的代码:

$query =DB::table('student')
            ->join('relation','relation.id_student_girl', '=', 'student.id')
            ->join('relation','relation .id_student_boy ', '=', 'student.id')
            ->select('student.*','relation.*')
            ->get();

我在此查询中出现错误任何想法,如何实现。 我希望我能够解决我的情况。 谢谢

尝试这个:

$query =DB::table('student')
->join('relation', function($join)
{
    $join->on('relation.id_student_girl', '=', 'student.id')
       ->orOn('relation.id_student_boy ', '=', 'student.id');
})->select('student.*','relation.*')->get();

即使这样做确实可行,我认为您的数据库结构也很糟糕。 为什么您的关系表具有id_student_boy和id_student_girl列? 2列之间有关系吗?

您可以使用此代码轻松获得所有关系数据。

App\Student::with('relation')->get();

但是要运行此代码,您需要在模型中描述表关系。 检查这个

$books = App\Book::with('author')->get(); 

暂无
暂无

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

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