所以有三个表:
Schema::create('files_urls', function (Blueprint $table) {
$table->increments('id');
$table->integer('file_id')->unsigned();
$table->foreign('file_id')->references('id')->on('files');
$table->string('filename');
$table->timestamps();
});
public function up()
{
Schema::create('files', function (Blueprint $table) {
$table->increments('id');
$table->timestamp('date');
$table->string('name');
$table->string('description');
$table->integer('group_id');
$table->timestamps();
});
}
Schema::create('groups', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('course_id');
$table->timestamp('start_date')->nullable();
$table->timestamp('end_date')->nullable();
$table->timestamps();
});
着陆页控制器如下所示:
public function listFiles($id){
$group = Group::find($id);
$data ['gInfo'] = $group;
$files = Group::find($id)->file;
$data ['fInfo'] = $files;
return view('upload.files', $data);
}
在刀片文件中循环:
@foreach ($fInfo as $file)
<tr>
<td>{{$file->date}}</td>
<td>{{$file->name}}</td>
<td>{{$file->description}}</td>
@foreach($file->file as $url)
{{$url->file->filename}}
@endforeach
</tr>
@endforeach
基本上,我想打印文件中的所有信息(可能名称不在这里 - 应该称为课程或其他东西)。但是,1课(文件)可以有几个名称(来自files_urls表)。所以它应该在每个课程(文件)的一行中的files_urls表中打印日期,名称,描述和所有名称。
关系是这样的:
class FilesUrl extends Model
{
protected $fillable = ['file_id', 'filename'];
public function file()
{
return $this->belongsTo('App\File');
}
}
public function file(){
return $this->hasMany('App\File');
}
提前谢谢。
答案 0 :(得分:1)
看起来您的模型关系设置不正确,或者您正确访问它们。
您还可以通过两次查询Group
模型来提高控制器的效率。
我假设您的数据库架构中Group
有很多File
个而File
有很多FilesUrl
个。
<?php
// app/Group.php
namespace App;
class Group extends Model
{
// ...
public function files()
{
return $this->hasMany(App\File::class);
}
// ...
}
// app/File.php
namespace App;
class File extends Model
{
// ...
public function group()
{
return $this->belongsTo(App\Group::class);
}
public function urls()
{
return $this->hasMany(App\FilesUrl::class)
}
// ...
}
// app/FilesUrl.php
namespace App;
class FilesUrl extends Model
{
// ...
public function file()
{
return $this->belongsTo(App\File::class);
}
// ...
}
// app/Http/Controllers/LandingPageController.php
namespace App\Http\Controllers;
class LandingPageController extends Controller
{
// ...
public function listFiles($id)
{
$group = Group::with('files.urls')->findOrFail($id);
return view('upload.files', compact('group'));
}
// ...
}
// resources/views/upload/files.blade.php
@foreach ($group->files as $file)
<tr>
<td>{{$file->date}}</td>
<td>{{$file->name}}</td>
<td>{{$file->description}}</td>
<td>
@foreach($file->urls as $url)
{{$url->filename}}
@endforeach
</td>
</tr>
@endforeach
@endforeach