2017-10-17 143 views
0

我有2個表「項目」和「品牌」。商品包含產品詳細信息,如item_id,name和brand_id,而品牌包含brandId和brand_name。我想獲取可加入品牌和商品的商品數據。ORM在laravel 5.4不工作

這是我的控制器。

public function filters($id){ 
    $items = Items::brands();  
    return $items; 
} 

這是我的模型。

public static function brands(){ 
    return $this->hasOne('App\Brands'); 
} 

我在瀏覽器上運行時遇到以下情況。 當不在對象範圍內使用$此

+1

你有一個靜態方法,並使用了$這個了,爲什麼你覺得會發生什麼? – madalinivascu

回答

0

刪除static關鍵字

public function brand(){ 
    return $this->hasOne('App\Brands','brand_id'); 
} 

在你的品牌,你需要

public function item(){ 
    return $this->belongsTo('App\Items','brandId','brand_id'); 
} 

和控制器:

public function filters($id){ 
    $items = Items::all()->with('brands')->get();  
    return $items; 
} 
+0

我認爲物品'belongsTo'對品牌 –

+0

當我放時,工作正常。 public function brands(){ return $ this-> hasOne('App \ Brands','brand_id','brand_id'); } –

+0

你應該將它命名爲'品牌',因爲你有'1:1'1品牌1品牌, – madalinivascu

0

嘗試這樣的:

模型文件:

public function brands(){ 
    return $this->hasOne('App\Brands'); 
} 

和控制器這樣的:

public function filters($id){ 
    $items = Items::select("*")->with('brands')->get()->toArray();  
    return $items; 
}