1

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 Answer 1

4

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');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.