我的项目中需要一棵树。我有一个名为category的表,它的id有一个foriegn键。制作此表的雄辩代码是:
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('category_id')->nullable();
$table->string('title');
$table->timestamps();
$this->foreign('category_id')
->references('id')
->on('categories')
->onDelete('cascade');
});
这里有很多问题: 1.迁移错误:
PHP致命错误:调用未定义的方法 CreateCategoriesTable ::外国()
SELECT * FROM categories sub LEFT JOIN categories parent ON parent.id = sub.category_id
public function parent() { return $this->belongsTo(Category::class); }
答案 0 :(得分:3)
第一个问题:
$this->foreign('category_id') to
$table->foreign('category_id')
第二个问题:
\DB::table('categories as sub')->leftJoin('categories as parent', 'parent.id','=','sub.category_id')->get();
第三个问题:
return $this->belongsTo(Category::class, 'id', 'parent_id');