简体   繁体   English

如何最好地实现一对多关系 Laravel

[英]How to best implement one to many relationship Laravel

I am working with Laravel for the backend.我正在使用 Laravel 作为后端。 I am wanting to save a model, let's say it is Shirts to my database.我想保存一个 model,假设它是我的数据库中的衬衫。 A shirt can have many different sizes, so i want to be able to save a record of shirts like so into my database:一件衬衫可以有许多不同的尺寸,所以我希望能够将这样的衬衫记录保存到我的数据库中:

{
   "name": "A good shirt",
   "descripton": "this shirt is very good",
   "price": "$100",
   "sizes": ["XL","L","M","S"]  <--------- what I want
}  

My question is, how can I save implement this in my backend?我的问题是,我怎样才能在我的后端保存实现这个? How can I save an array of different sizes to my model AND make sure that when this record is saved, it meets one of the available shirt sizes?如何将不同尺寸的数组保存到我的 model 并确保保存此记录时,它符合可用的衬衫尺寸之一? For example, I want to make sure that a shirt can only have sizes from small to extra large.例如,我想确保一件衬衫只能有从小到大的尺寸。

I thought about creating a new model called Shirt_Sizes and having the records be the available shirt sizes, then setting a foreign key in my Shirt Model to this.我考虑创建一个名为 Shirt_Sizes 的新 model 并将记录作为可用的衬衫尺寸,然后在我的 Shirt Model 中设置一个外键。 But I am having a difficult time figuring out how to save many shirt sizes to the Shirt model.但是我很难弄清楚如何将许多衬衫尺寸保存到 Shirt model 中。

I am open to other suggestions that work outside of this.我愿意接受除此之外的其他建议。

Thank you!谢谢!

If a shirt has many sizes and the sizes can belong to many shirts then you must Define a many to many relationship, You can make a separate table sizes for shirts sizes and then create a second table shirt_size that contains shirt_id & size_id link them with a foreign key to your shirts & sizes table.如果一件衬衫有很多尺码并且这些尺码可以属于很多衬衫,那么您必须定义多对多关系,您可以为衬衫尺码制作一个单独的表sizes ,然后创建第二个表shirt_size包含shirt_idsize_id将它们与您的shirtssizes表的外键。

Then you will define the appropriate relationships between the two models然后您将定义两个模型之间的适当关系

Size Model尺寸 Model

class Size extends Model
   {
   // Get the shirts for this size.
   public function shirts()
   {
       return $this->belongsToMany(Shirt::class, 'shirt_size', 'size_id', 'shirt_id');
   }
} 

Shirt Model衬衫 Model

class Shirt extends Model
{
   // Get the size for the shirt.
   public function sizes()
   {
        return $this->belongsToMany(Size::class, 'shirt_size', 'shirt_id', 'size_id');
   }
}

Then when you need to store a new shirt with the sizes, it depends on what you send with your request:然后,当您需要存储具有尺寸的新衬衫时,这取决于您随请求发送的内容:

  1. Sending an array of sizes ids :发送一个大小ids的数组:

    Then you will need to verify the ids using validate :然后您需要使用validate验证 id:

 $validatedData = $request->validate([
     'sizes.*.size_id' => 'required|integer|exists:sizes,id',
 ]);
  1. Sending an array of sizes names :发送尺寸names数组:

    Then you will need to verify the names using validate :然后您需要使用validate验证名称:

 $validatedData = $request->validate([
     'sizes.*.size_name' => 'required|string|exists:sizes,name',
 ]);

Then after creating a shirt record you can use an the attach() method to save multiple sizes for a shirt:然后在创建衬衫记录后,您可以使用attach()方法为衬衫保存多个尺寸:

foreach ($validatedData['sizes'] as $size){
   $shirt->sizes()->attach($size['size_id']);
}

Or或者

foreach ($validatedData['sizes'] as $size){
   $size_id  = Size::where('size_name',$size['name'])->get('id'));
   $shirt->sizes()->attach($size_id);
}

The scenario you have is many-to-many relationships, that is, a shirt can have many sizes and one size can have many shirts, so I recommend creating two table tables as specified by the Laravel documentation.您的场景是多对多关系,也就是说,一件衬衫可以有多种尺码,而一种尺码可以有多种衬衫,因此我建议按照 Laravel 文档的规定创建两个表格。 https://laravel.com/docs/7.x/eloquent-relationships#many-to-many https://laravel.com/docs/7.x/eloquent-relationships#many-to-many

 shirt id - integer name - string description - string price - integer sizes id - integer name - string sizes_shirts shirt_id - integer size_id - integer

Your models look like:您的模型如下所示:

 <?php namespace App; use Illuminate\Database\Eloquent\Model; class Shirt extends Model { /** * The sizes that belong to the shirt. */ public function sizes() { return $this->belongsToMany('App\Size'); } }

How to save sizes for a shirt:如何节省衬衫的尺码:

$sizes_ids = [1, 2, 3];
$shirt->sizes()->sync($sizes_ids);

How to get sizes for a shirt:如何获得衬衫的尺码:

$sizes_of_shirt = $shirt->sizes;

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

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