php - 使用 Laravel 在其他表中显示产品名称

标签 php mysql laravel laravel-5 eloquent

我再次请求您的帮助。

我想将分支产品与数量分组,但是,我无法将产品名称显示为产品名称。截至目前,我显示的是产品 ID,而不是产品名称

   +-----------------+   +-----------------+    +----------------+ 
  |  product table  |   | quantity table  |    |  branch table  |
  +-----------------+   +-----------------+    +----------------+
  |   id            |   |  prod_id      |    |   id           |
  |   productname   |   |  branch_id       |    |   branchname   |
  +-----------------+   |  quantity       |    +----------------+
                        +-----------------+

分支模型

public function products()
    {
        return $this->hasMany('App\Quantity', 'branch_id');
    }

数量模型

public function branch()
    {
        return $this->belongsTO('App\Branch', 'branch_id', 'id');
    }

产品型号

public function productquantities()
    {
        return $this->hasMany('App\Quantity','prod_id');
    }

我的观点

@foreach($dataBranch as $Branch)
            <h1>Branch {{$Branch->branch_name}}</h1>
            <table class="table table-striped table-bordered">
                <thead>
                  <tr>
                    <th>  </th>
                    <th>Product Name</th>
                    <th>Quantity</th>
                  </tr>
                </thead>
                <tbody>
                  @forelse($Branch->products as $Product)
                  <tr>
                  <td align="center" style="text-align:center"> <a href="#" class="avatar"><img src="{{ asset('productimg') }}/" width="100px"/> </a> </td>
                    <td> <a class="name">{{$Product->prod_id}} //this should be the product name instead of product id</a></td>
                    <td><em class="productprice">{{$Product->quantity}}</em>  </td>

                   </tr>
                   @empty
                   <tr><td colspan='4'><em>No Data</em></td></tr>
                  @endforelse


                </tbody>
              </table>
            @endforeach 

我的 Controller

  $dataBranch = Branch::with('products')->get();

enter code here

最佳答案

截至目前,您正在使用数量表而不是产品表加入分支。您可以在您的 Branch 模型中执行如下操作(未经测试)。这个想法是通过数量从分支到产品的连接。

public function productsThroughQuantity() {
    // The columns need to be added
    return $this->hasManyThrough('App\Products', 'App\Quantity', <columns>);
}

但是,我发现的一个问题是,如果您这样做,您可能会收到有关分支和产品 id 字段的不明确列的 SQL 警告。我将在您的产品表 id =>product_id 和分支表 id =>branch_id 中重命名。在数量表中将branch_id重命名为branch_table_id之类的名称。

然后在您的分支和产品模型中:

protected $primaryKey = "<branch/products>_id";

关于php - 使用 Laravel 在其他表中显示产品名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51827958/

相关文章:

php - 在 Laravel 邮件中设置主题变量

MySQL数据库右移

mysql - 数据库性能调整有哪些资源?

php - Laravel 家园

php - 输入类型 ="file"更改后是否可以重新加载表单?

php - .htaccess不适用于所有链接

PHP Laravel 错误 : Object of class stdClass could not be converted to string

mysql - 使用 DBI 在 R 中进行日期循环查询

php - 将通配符传递给 Laravel 4 中的路由

laravel - 为什么 Apache(centos 7) 看不到我创建的路由?