2016-11-15 52 views
-1

我創建一個遷移如下:組關係中laravel

Category::create([ 
     'id' => 1, 
     'parent' => null, 
     'category_name' => "root" 
    ]); 

    Category::create([ 
      'id' => 2, 
      'parent' => 1, 
      'category_name' => "something" 
     ]); 

    Category::create([ 
     'id' => 3, 
     'parent' => 2, 
      'category_name' => "something" 
      ]); 
    Category::create([ 
     'id' => 4, 
     'parent' => 2, 
      'category_name' => "something" 
      ]); 

    and etc ... 

也這是我的模型,它是自引用:

public function up() 
{ 
    // 
    Schema::create('categories', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->unsignedInteger('parent')->nullable()->unsigned();; 

     $table->string('category_name'); 
     $table->text('category_lable'); 
     $table->timestamps(); 
}); 
    Schema::table('categories', function (Blueprint $table) { 

     $table->foreign('parent') 
      ->references('id')->on('categories') 
      ->onDelete('cascade') 
      ->onUpdate('cascade'); 
    }) ; 
} 

和遷移是通過這種方式接種:

class Category extends Model 
{ 
public function getchildren() { 
    return $this->has_many('App\Category' , 'parent'); 
} 
public function getparent() { 
    return $this->belongs_to('App\Category' , 'parent'); 
} 

}

在修補程序中,當我嘗試獲取某個節點父節點或子節點時,出現錯誤。

錯誤:

BadMethodCallException與消息 '調用未定義方法照亮\數據庫\查詢\生成器::的getParent()'

BadMethodCallException與消息「調用未定義的方法Illuminate \ Database \ Query \ Builder :: getchildren()'

我的錯在哪裏?

回答

0

首先,關係方法應該是駝峯

public function getchildren() { 
    return $this->hasMany('App\Category' , 'parent'); 
} 
public function getparent() { 
    return $this->belongsTo('App\Category' , 'parent'); 
} 

其次,錯誤是存在的,因爲你可能要求這些關係的錯誤的方式。您在Builder實例上調用這些方法,而不是Model實例。

它應該是這個樣子:

$category = Category::first(); 

var_dump($category->getchildren, $category->getparent); 

或者:

foreach(Categories::all() as $category) { 
    var_dump($category->getchildren, $category->getparent); 
} 

無論如何,如果你可以分享你在廷克輸入的代碼,我們可以準確地找出問題所在。

編輯

您應該重命名方法children()parent(),所以沒有得到前綴。

而且,直接檢索這個關係,稱他們爲財產,而不是一個方法:

$model = Category::findOrFail(26); 

// this will return Builder instance 
var_dump($model->children(), $model->parent()); 

// this will return the return a Collection of children 
var_dump($model->children); 

// this will return the parent 
var_dump($model->parent); 

不同的是()。

+0

tnanks @ jan-willem請留意。這裏是我的:$ cat = Category :: findOrFail(26)然後:$ cat-> children() – user3634011

+0

查看我更新的答案。 –

+0

它返回null:((($ model-> children) – user3634011