【问题标题】:View and Controller for a Downloadpage下载页面的视图和控制器
【发布时间】:2021-03-16 12:18:35
【问题描述】:

我需要创建一个下载页面。我有一个模型产品和一个模型文件。创建/存储和编辑/更新已经在工作。通过提交按钮,我将产品名称、描述等字段保存到产品表中。文件名、文件路径和产品 ID 等字段保存到文件表中。文件也上传到存储。 Model Product 与 File 有一个 hasMany-relation,而 Model File 与 Product 有一个 BelongsTo-relation。在文件模型中,“product_id”与产品模型相关。

到目前为止一切顺利。同样有效的是:FileController 的索引视图。我可以看到所有上传的文件,也可以下载它们。通过 product_id 我可以访问实际的产品展示方法。应该是这样的。在 index.blade.php 中是可能的:

@foreach ($files as $file)                                         
<tr>                                             
    <th>{‌{ $file->filename }}</th>
    <td><a href="{‌{ $file->filepath }}">download</a></td>
    <td><a href="/products/{‌{ $file->product_id }}">{‌{ $file->product_id }}</a></td>
    <td>{‌{ $file->id }}</td>
</tr>                                        
@endforeach

在 show.blade.php 中,我已经可以看到 products 表中的所有数据。我有两个按钮用于下载更改日志(只是一个链接)和工作以及下载存储的文件(在文件表中。我无法让它为下载存储的文件工作。dd($files); 为 NULL。这是 ProductController显示部分。我在控制器顶部应用了use App\File;,因为我想提供访问文件模型的能力。

public function show(Product $product)     
{                 
         return view('products.show', compact('product','file'));     
}

在 show.blade.php 中出现错误:compact(): Undefined variable: file

<div>
    <button id="changelog" name="changelog" class="btn btn-lg btn-primary btn-block" type="submit" onclick="window.open('{‌{ $product->changelog }}')">Download Changelog</button>
    <button id="filename" name="filename" class="btn btn-lg btn-success btn-block" type="submit" onclick="window.open('{‌{ $file->filename }}')">Download Installer</button>
</div>

如何访问其他模型或其他表格的元素?如何扩展 {‌{ $file-&gt;filename }} 或可能是 {‌{ $product-&gt;$file-&gt;filename }} 以获取要下载的文件?

我一直在尝试,但找不到解决方案。

【问题讨论】:

  • 请附上您的产品型号和文件型号
  • 因为你没有在show函数上定义$file变量

标签: laravel


【解决方案1】:

谢谢,回复。我在构建 Eloquent 和 Query 时仍然遇到问题,但是使用 dd od var_dump 帮助很大,并向我展示了我拥有有价值的数据。问题是定义查询。 这是工作的东西:

产品型号

public function file()
    {
        return $this->hasMany('App\File', 'product_id');
    }

文件模型

public function product()
    {
        return $this->hasOne('App\Product', 'id');
    }

产品控制器

public function show(Product $product)
    {
$files = Product::with('file')->find($product->id)->file;
return view('products.show', compact('product', 'files'));
    }

显示视图

@foreach ($files as $file)
      <button id="filepath" name="filepath" class="btn btn-lg btn-success btn-block" type="submit" onclick="window.open('{{ $file->filepath }}')">Download File:  {{ $file->filename }}</button>
@endforeach

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多