简体   繁体   English

如何在数据库Laravel中联接两个表

[英]how to join two tables in database Laravel

I'm trying to join two tables (products table and Images table), so in products table each product has multiple images(stored in a row named image) so I want to display images of each product in images table . 我试图连接两个表(产品表和图像表),因此在产品表中每个产品都有多个图像(存储在名为image的行中),因此我想在images table显示每个产品的images table In images table I have a foreign key named product_id references(id) on products table, The problem is it can't store images in images table,(it keeps storing images in the row(image) in products table). 在图像表中,我在产品表上有一个名为product_id (id)的外键,问题是它无法在图像表中存储图像(它一直将图像存储在产品表的行(图像)中)。 How do I solve this? 我该如何解决?

Codes 代码

Product.php Product.php

public function images()
 {
   return $this->hasMany('App\Image', 'product_id');
 }

Image.php Image.php

public function product()
{
  return $this->belongsTo('App\Product','product_id');
 }

Controller 调节器

 public function store(Request $request) 
 { 

$Input=$request->all();
$image=array();
if($files=$request->file('image')){
foreach($files as $file){
    $name=$file->getClientOriginalName();
    $file->move('images',$name);
    $image[]=$name;
  }
  } 
 product::create(array_merge($Input,
 [
 'image' => json_encode($image),

 ])); 
return redirect()->back(); 

}

Any help will be appriciated. 任何帮助将被申请。

If you are trying to save the image to the images table, and you are instead 'it keeps storing images in the row(image) in products table' - you are saving the wrong item. 如果您试图将图像保存到图像表中,而是“它一直将图像存储在产品表中的行(图像)中”,那么您将保存错误的项目。 You appear to have the correct structure - with one to many in your models. 您似乎具有正确的结构-模型中有一对多的结构。 Just need to save the Image rather than the Product 只需要保存图像而不是保存产品

Something like this will fix this issue: 这样的事情会解决这个问题:

Image::create(['whateverYouNeedToSave', 
              'product_id'=>$product_id,      <-- Connect the product here, within the image
              'etc']);

It is actually possible to do this by creating the Product and then saving the Images as a relation, but this might not be the cleanest / easiest way to architect this - suggest you start with saving the Image , as you will have many of them, vs. just one Product at a time. 实际上,可以通过创建产品 ,然后将图像保存为关系来完成此操作,但这可能不是构造此方法的最干净/最简单的方法-建议您从保存图像开始,因为您将拥有许多图像 ,一次只能对比一个产品 Then, after this works, and is clear / comfortable, you can try it the more 'advanced' way if you need to. 然后,在此方法奏效且清晰/舒适之后,如果需要,您可以尝试使用更“高级”的方法。

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

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