简体   繁体   English

在laravel中有很多工具

[英]has many implement in laravel

I find myself starting with laravel and I need a little help from the following: I have a one-to-many relationship between: a product can have multiple images at the same time, an image belongs to a product. 我发现自己从laravel开始,我需要以下帮助:我之间存在一对多关系:一个产品可以同时具有多个图像,一个图像属于一个产品。 code: 码:

Product: 产品:

class Product extends Model
{
  public function images(){
    return $this->hasMany('App\Image');
  }
}

Image: 图片:

class Image extends Model
{
  public function product(){
    return $this->belongsTo('App\Product');
  }
}

Now to show the View I want to show only the first image of each product, I do this in the controller: 现在,为了显示视图,我只想显示每个产品的第一张图片,我在控制器中执行以下操作:

public function index()
{
  $products = Product::all();
  $products = Product::join('images', 'products.id', '=', 'images.id')->select('products.id','products.denomination_prod','products.description','pooducts.price','images.path')
  ->get();

  return view('products.products', compact('products'));
}

Now you could tell me if this is done correctly. 现在,您可以告诉我是否正确完成了操作。 That is I am respecting the standards of good structure?. 那是我遵守的良好结构标准吗? I hope you can help me; 我希望你能帮帮我; perhaps a silly question for many but they are my first steps with this excellent framework and would like to learn it the right way. 对于许多人来说,这可能是一个愚蠢的问题,但这是我采用这个出色框架的第一步,并希望以正确的方式学习它。

There is no need to use join() . 无需使用join() You can just use the declared relationship: 您可以只使用声明的关系:

$products = Product::with('images')->get();

and then you are going to have an images collection per product. 然后您将为每个产品收集图像。 Afterwards you can do whatever you like with each product's images collection. 然后,您可以对每个产品的图像集进行任何操作。 A simple loop might be useful: 一个简单的循环可能会有用:

@foreach($products as $product)
    <div class="col-lg-4 col-md-6 col-xs-12">
        <img src="{{asset($product->images->first())}}" />
    </div>
@endforeach

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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