2014-10-09 96 views
0
我在與輸出的關係數據,我試圖讓從producttypes類它說,試圖讓非對象的屬性稱號問題

,我已經試過各種方法,但我不獲得期望的結果laravel父的關係屬於關聯

class Product extends \Eloquent { 

    public function producttype() { 
     return $this->belongsTo('ProductTypes', 'producttype_id'); 
    } 

} 

class ProductTypes extends \Eloquent { 

    public function products() { 
     return $this->hasMany("Product", 'id'); 
    } 
} 

$product->producttype->title 

更新

class ProductTypes extends \Eloquent { 
    protected $fillable = ['keywords', 'description', 'title', 'slug']; 
    protected $table = "producttypes"; 

    public function products() { 
     return $this->hasMany("Product", 'product_id', 'id'); 
    } 
} 

class ProductVariations extends \Eloquent { 
    protected $table = "productvariations"; 
    protected $fillable = ['product_id', 'producttype_id', 'price', 'quantity', 'discount', 'image']; 


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

public function show($id) 
{ 
    $product = Product::with('producttype')->findOrFail($id)->get(); 

    return View::make('products.show')->withProduct($product); 
} 

顯示頁面

$product->producttype->title 
+0

顯示你的表。 – 2014-10-09 06:31:39

回答

0

你有以這種方式獲取數據庫值

$product = Product::with('producttype')->get() 

試試這個。

請把這個代碼在你routes.php文件文件在一切的底部..只是用於測試目的。

Route::get('/', function(){ 
    $product = Product::with('producttype')->get(); 
    dd($product); 
}); 

get()方法將返回帶有多個對象的數組中的結果,並且firstOrfail將僅返回對象。這就是爲什麼你得到非對象方法調用異常。嘗試dd()結果集,你會知道

+0

確切地說,我把這個函數放在哪裏,試圖把它放在productstypes()中的產品類中,我得到這個錯誤達到'100'的最大函數嵌套級別,正在中止! – ONYX 2014-10-09 05:15:22

+0

在產品類中,productstypes()是您定義了belongsTo關係的函數。在你的路由文件中試試這個,我只是爲了測試目的而更新我的答案。 – justrohu 2014-10-09 05:19:19

+0

我在show route $ product = Product :: findOrFail($ id) - >中添加了這個('producttype') - > get(); – ONYX 2014-10-09 05:21:18

0

你應該確保查詢返回的是對象而不是集合。如果您正在使用where查詢,則會獲得對象集合,除非您在查詢中添加 - > firstorfail()。 如果您使用'Model :: Find(id)',那麼您將獲得該對象,因此您可以使用該方法。 看看querying-relations該部分末尾的紅色筆記。

你應該嘗試

public function show($id) 
{ 
    $product = Product::Find($id); 

    return View::make('products.show',['product'=>$product]); 
} 

您認爲這些產品的方法將可以訪問

$product->producttype; 
$product->productvariation //You should add this method to the product class 
+0

我編輯我的答案,看看 – geoandri 2014-10-09 05:42:01