I\'m working on a project in Laravel. I have an Account model that can have a parent or can have children, so I have my model set up like so:
public
For future reference:
public function parent()
{
// recursively return all parents
// the with() function call makes it recursive.
// if you remove with() it only returns the direct parent
return $this->belongsTo('App\Models\Category', 'parent_id')->with('parent');
}
public function child()
{
// recursively return all children
return $this->hasOne('App\Models\Category', 'parent_id')->with('child');
}
This is for a Category
model that has id, title, parent_id
. Here's the database migration code:
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('title');
$table->integer('parent_id')->unsigned()->nullable();
$table->foreign('parent_id')->references('id')->on('categories')->onUpdate('cascade')->onDelete('cascade');
});