【问题标题】:Laravel Join Related Product ImagesLaravel 加入相关产品图片
【发布时间】:2014-11-18 15:24:01
【问题描述】:

我有两张桌子:

product:id | name | category

productimage:id | imagename | productid

我想以这种形式获取结果:

[{
 "id":1,
 "name":"abc",
 "category":1,
 "imagename":[
    {
      "id":1,
      "imagename":abc.jpg
    },
    {
      "id":2,
      "imagename":abc1.jpg
    },
    {
      "id":3,
      "imagename":abc2.jpg
    }]
}]

我有两个模型:

call:

= product
= productimage

<?php

class Product extends \Eloquent {
    //protected $fillable = [];
    protected $table = 'product';


    public function productimage(){
        return $this->hasMany('productimage');
    }

}

<?php

class Productimage extends \Eloquent {
    //protected $fillable = [];
    protected $table = 'productimage';

    public function product(){
        return $this->belongsTo('product');
    }
}

【问题讨论】:

  • 很好。你试过什么?
  • 你应该阅读 Laravel 文档中的关系 laravel.com/docs/4.2/eloquent#relationships
  • 不清楚您的问题是什么,或者您的问题...阅读文档,尝试,并在遇到特定问题时询问。
  • 我的问题不知道怎么加入product::find(id)->productimage;

标签: php mysql sql laravel eloquent


【解决方案1】:

这是直接取自Laravel documentation:

在模型中定义关系,我假设一个产品只能有一个产品图片:

class Product extends Eloquent {

    public function productimage()
    {
        return $this->hasOne('Productimage');
    }

}

获取 ID 为 1 的产品的产品图片:

$image = Product::find(1)->productimage;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-15
    • 2019-12-25
    • 2021-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    相关资源
    最近更新 更多