2014-09-24 67 views
-1

我有兩個表:Laravel加入相關產品圖像

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

這很好。你有什麼嘗試? – Joe 2014-09-24 08:09:05

+0

您應該閱讀關於Laravel文檔中的關係http://laravel.com/docs/4.2/eloquent#relationships – 2014-09-24 08:15:02

+0

不清楚您的問題是什麼,或者您的問題......閱讀文檔,嘗試和詢問何時遇到特定問題。 – 2014-09-24 09:00:50

回答

0

這是直接取自Laravel documentation

在模型中定義的關係,我認爲一個產品只能有一個產品形象:

class Product extends Eloquent { 

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

} 

獲取產品產品ID爲1的圖像:

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