2016-11-15 54 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