简体   繁体   中英

how to get data for two tables in laravel 5.2

I was working with Laravel and got stuck in a situation. I have following tables: student table and relation table student table has the following columns id,name,sex,age,and class

relation table has the following columns id,id_student_girl,id_student_boy and status

i need to display output look like this: name_student_girl,name_student_boy and status

code i tried :

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

I got errors on this query Any idea, how to achieve this. I hope I was able to clear my situation. Thanks

Try this:

$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();

Even if this does work, I think it's a very bad database structure that you have. Why does your relation table have a id_student_boy and id_student_girl column? Is there a relationship between the 2 columns?

you can get all relational data so easily with this code..

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

but for run this code you need to describe your table relation in your model. check this

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

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