Laravel加入相关产品图片

时间:2014-09-24 08:07:59

标签: php mysql sql laravel eloquent

我有两张桌子:

productid | name | category

productimageid | 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');
    }
}

1 个答案:

答案 0 :(得分:0)

直接来自Laravel documentation

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

class Product extends Eloquent {

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

}

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

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