jeudi 14 septembre 2017

can I get children on same model where parent belongs to another model

I have a model where child models have this relationship with parent:

public function children()
{
    return $this->hasMany(self::class, 'parent_id', 'unique_id')->orderBy('id', 'asc');
}

my table looks like this:

        $table->increments('id');
        $table->integer('project_id')->unsigned();
        $table->string('type');
        $table->unsignedBigInteger('unique_id');
        $table->bigInteger('parent_id')->unsigned()->nullable();
        $table->integer('order')->nullable();
        $table->timestamps();

        $table->unique(['unique_id', 'project_id'], 'abcd')->unsigned();

        $table->foreign('project_id')->references('id')->on('projects')->onUpdate('cascade')->onDelete('cascade');

unique_id field is only unique per project, which is why I did this: $table->unique(['unique_id', 'project_id'], 'abcd')->unsigned();

however the relationship defined earlier fails if I have 2 projects, 2 parents belonging to separate projects and two child models belonging to parents

Project 1
Project 2

Model 1
    uniqueId: 123
    projectID: 1

Model 2
    uniqueId: 1234
    parentId: 123
    projectId: 1


Model 3
    uniqueId: 123
    projectID: 2

Model 4
    uniqueId: 1234
    parentId: 123
    projectId: 2

When I load the edit page for project 1, I see Model 1 with two child models: Model 2 and Model 3

how can I in definition of children relationship define that relationship is only valid if they belong to the same project?

I have tried this instead

public function children()
{
    return $this->hasMany(self::class, 'parent_id', 'unique_id')->where('project_id', $this->project_id)->orderBy('id', 'asc');
}

but it failed, I did dump($this->project_id) and that prints null. So project_id is not available at that point it seems and I can't restrict what is being returned?

Anyone has an idea how to solve this?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire