2016-07-21 33 views
0

我是新來的laravel,目前正在使用ORM我想通過使用類別表中存在的外鍵從parentCategory表中檢索數據。Macroable.php第81行中的BadMethodCallException:方法不存在。 Laravel ORM

以下是我的類別模型的代碼:以下

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class category extends Model 
{ 
    protected $table='category'; 

    public function parentCategory(){ 

     return $this->belongsTo('App\parentCategory','mCategoryId'); 

    } 

} 

是我parentCategory型號代碼:

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class parentCategory extends Model 
{ 
    protected $table='maincategory'; 



    public function categories(){ 

     return $this->hasMany('App\category'); 

    } 

} 

以下是我categoryController的代碼由我使用的檢索數據:

class categoryController extends Controller 
{ 
    function index(){ 

     $category=category::all()->with('parentCategory'); 
     $parentCategory=parentCategory::all(); 
     return view('admin.category',['categories'=>$category,'parentCategories'=>$parentCategory]); 

    } 

    function add(Request $request){ 

     $category= new category(); 
     $category->categoryName=$request["name"]; 
     $category->mCategoryId=$request["parentCategory"];  
     $category->save(); 
     return redirect()->route('category'); 

    } 
} 

該錯誤進一步說明: 在收藏 - > __通話( '有',陣列( 'parentCategory'))在categoryController.php線17

+0

您正在使用哪種Laravel版本? – Samsquanch

回答

0

在你index()功能,你可以嘗試

$category = category::with('parentCategory')->get(); 

這應該解決問題。按照Eager Loading文檔。

相關問題