【问题标题】:What is the most effiecient way to display a one-to-one relationship [Laravel]显示一对一关系的最有效方法是什么[Laravel]
【发布时间】:2021-04-07 04:22:51
【问题描述】:

有两个表具有一对一关系:ProductsDescriptions。 控制器返回刀片视图中的两个表。

我使用 foreach 循环来显示 Products 表。

   @foreach($products as $product)  
                  ...       
          {{ $product->name }}
          {{ $product->price }}
                  ...
   @endforeach

我也想显示每个产品的描述

   @foreach($products as $product)  
                  ...       
          {{ $product->name }}
          {{ $product->price }}
                  ...
          {{ $description}}
   @endforeach

在哪里description->product_id == $product->id

我曾想过在每个循环中使用嵌套的 foreach 循环或从刀片文件中查询,但似乎效率不高。

有没有更好的办法?

[注意:并非每个产品都有描述]

【问题讨论】:

  • 你可以使用 laravel 预加载不连接数据库每次你想得到产品的描述 $products::with('description')->all() 然后你可以访问它在 foreach 这样的 $product->description 中,您可以从 laravel doc laravel.com/docs/8.x/… 中阅读更多内容

标签: php laravel laravel-blade laravel-livewire


【解决方案1】:

我认为您需要将产品模型中的关系添加为:

use Description; // this is your Description model
class Product {
...
public function productDescription(){
  return $this->hasOne('Description','product_id','id'); 
// hasOne here because you want a one to one
}
...
}

当你想调用产品时:

$products = Products::with('productDescription')->get()->toArray();

现在在迭代产品时,从产品项中获取每个产品的描述:

$description = $product->productDescription;

编辑:对于您上面的html,这里是一个例子:

@foreach($products as $product)      
  {{ $product->name }}
  {{ $product->price }}
  {{isset($product->productDescription->name) ? $product->productDescription->name : '' }}
  <!-- name key is just an example here -->
@endforeach

【讨论】:

    【解决方案2】:

    我曾经使用 twig,但你为什么不使用类似的东西

    @if(isset($descriptions[$product->id]))
        {{ $descriptions[$product->id] }}
    @endif
    

    你不能在刀片中?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-12
      • 1970-01-01
      • 2015-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多