drwpbrv668670 2017-05-15 08: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 08: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().

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部