使用 Laravel5 连接表格和打印数据
Joining tables and printing data using Laravel5
正在尝试打印有关包和属于每个包的属性的数据。
使用连接 table 连接另外两个 table。
当尝试使用属于每个包的单独属性打印每个包时,会为每个包打印所有包的所有属性。
控制器方法:
public function index()
{
$packages = Package::all();
$courses = DB::table('course_package')
->join('package', 'course_package.Package_Id', '=', 'package.Id')
->join('course', 'course_package.Course_Id', '=', 'course.Id')
->select('course_package.*', 'package.*')
->get();
return View::make('admin.package.index')
->with('packages', $packages)
->with('courses', $courses);
}
查看:
@foreach($packages as $package)
<tr>
<td>{{ $package->Id }}</td>
<td>{{ $package->title }}</td>
<td>{{ $package->description }}</td>
<td>{{ $package->university }}</td>
<td>{{ $package->faculty }}</td>
@foreach($courses as $course)
@if($course->Package_title = $package->title)
<tr>
<td>{{$course->Course_name}}</td>
</tr>
@endif
@endforeach
@endforeach
我需要做什么才能将属于某个包的所有课程与特定包一起打印?
Laravel 开箱即用 Relationships,好好利用吧!
套餐和课程是many-to-many relationship,以course_package
为支点table(中级Table).
package.php
class Package extends Model
{
public function courses() {
return $this->belongsToMany('App\Course', 'course_package', 'Package_Id', 'Course_Id');
}
}
查看
@foreach ($packages as $package)
...
@foreach ($package->courses as $course)
...
@endforeach
@endforeach
正在尝试打印有关包和属于每个包的属性的数据。
使用连接 table 连接另外两个 table。
当尝试使用属于每个包的单独属性打印每个包时,会为每个包打印所有包的所有属性。
控制器方法:
public function index()
{
$packages = Package::all();
$courses = DB::table('course_package')
->join('package', 'course_package.Package_Id', '=', 'package.Id')
->join('course', 'course_package.Course_Id', '=', 'course.Id')
->select('course_package.*', 'package.*')
->get();
return View::make('admin.package.index')
->with('packages', $packages)
->with('courses', $courses);
}
查看:
@foreach($packages as $package)
<tr>
<td>{{ $package->Id }}</td>
<td>{{ $package->title }}</td>
<td>{{ $package->description }}</td>
<td>{{ $package->university }}</td>
<td>{{ $package->faculty }}</td>
@foreach($courses as $course)
@if($course->Package_title = $package->title)
<tr>
<td>{{$course->Course_name}}</td>
</tr>
@endif
@endforeach
@endforeach
我需要做什么才能将属于某个包的所有课程与特定包一起打印?
Laravel 开箱即用 Relationships,好好利用吧!
套餐和课程是many-to-many relationship,以course_package
为支点table(中级Table).
package.php
class Package extends Model
{
public function courses() {
return $this->belongsToMany('App\Course', 'course_package', 'Package_Id', 'Course_Id');
}
}
查看
@foreach ($packages as $package)
...
@foreach ($package->courses as $course)
...
@endforeach
@endforeach