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 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了