1
votes

I need a tree in my project. I have a table named category and it has a foriegn key to its id. The eloquent code for making this table is:

 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');
    });

There is many problem here: 1. Error in migrate:

PHP Fatal error: Call to undefined method CreateCategoriesTable::foreign()

  1. How to alias tables so i can do this query:
    SELECT *
    FROM categories sub
    LEFT JOIN categories parent ON parent.id = sub.category_id
    
  2. Is there any way to define this relation on category model like:
    public function parent()
    {
        return $this->belongsTo(Category::class);
    }
    
1

1 Answers

4
votes

First problem:

$this->foreign('category_id') to
$table->foreign('category_id')

Second problem:

\DB::table('categories as sub')->leftJoin('categories as parent', 'parent.id','=','sub.category_id')->get();

Thrid problem:

return $this->belongsTo(Category::class, 'id', 'parent_id');