简体   繁体   中英

What is the most effiecient way to display a one-to-one relationship [Laravel]

There are two tables with a one-to-one relationship: Products and Descriptions . The controller returns the two tables in the blade view.

I use a foreach loop to display the Products table.

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

I want to display the description for each product, too

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

where description->product_id == $product->id

I thought of using nested foreach loops or querying from the blade file on every loop but it doesn't seem efficient.

Is there a better way?

[NOTE: Not every Product has a Description]

I think you need to add the relationship in product model as:

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
}
...
}

And when you want to call products:

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

Now while iterating the products, get each product's description from product item as:

$description = $product->productDescription;

EDIT : For your html above,here is an example:

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

i used to work with twig but why don't you use something like

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

in the blade you can't?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM