Laravel Recursive Relationships

后端 未结 7 2015
醉梦人生
醉梦人生 2020-11-28 21:22

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         


        
7条回答
  •  醉梦人生
    2020-11-28 21:47

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

提交回复
热议问题