drwpbrv668670 2017-05-15 16:25
浏览 40
已采纳

Laravel 5.4雄辩的一对多关系数据获取

I have two tables. 1.products 2.product_images.

Field of products Table: id,product_name,created_at,updated_at

Field of product_images Table: id,product_id,product_image,created_at,updated_at

products table has OnetoMany relationship with product_images table.

So in the Product model I have defined :

public function productImage()
{
    return $this->hasMany(Product_image::class,'product_id');
}

Now I want to to get all the data of product id 1 from both tables.

So I have this code below:

App\Product::find(1)->productImage

Result Set is:

Illuminate\Database\Eloquent\Collection {#689
     all: [
       App\Product_image {#679
         id: 1,
         product_id: 1,
         product_image: "1494787942_download (1).jpg",
         created_at: "2017-05-14 18:52:22",
         updated_at: "2017-05-14 18:52:22",
       },
     ],
   }

But I am not getting the product_name. What will be the solution? Thanks.

  • 写回答

1条回答 默认 最新

  • duanqiao1949 2017-05-15 16:51
    关注

    productImage doesn't have a product_name property, but product does. When you show the results of App\Product::find(1)->productImage; you can't expect it to show a product_name property.

    If you wanted to see the product and it's attached image, you would do this:

    $product = \App\Product::with(["productImage"])->find(1);
    

    Then, doing a dd($product) would show you the product (including the product_name attribute) and the productImage as an attribute that returns a Collection of productImage records.

    Keep in mind that have a function named productImage that returns multiple productImage records is misleading; naming convention would suggest productImages().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?