samedi 29 juillet 2017

Laravel's Seeder not able to insert data into Multi Level relationship

I have a base table named "Projects" And I have another table named "Project Blocks".

I have defined the relationship for projects to Project block as one to many. The Relationship is defined in this way :

namespace App;
use Illuminate\Database\Eloquent\Model;
class Projects extends Model
{
    public function projectblocks(){
        return $this->hasMany('App\ProjectBlocks','project_id','id');
    }
}

I also have one table Named "Project Units" which has realtionship with project block table:

namespace App;
use Illuminate\Database\Eloquent\Model;
class ProjectBlocks extends Model
{
    public function projects(){
        return $this->belongsTo('App\Projects','project_id','id');
    }

     public function projectunits(){
        return $this->hasMany('App\ProjectUnits');
    }
}

I have also defined the table structure inside ModelFactory :

$factory->define(App\Projects::class, function (Faker\Generator $faker) {    
    return [
        'name' => $faker->sentence(5),
        ...//All other required fields               
    ];
});

And

$factory->define(App\ProjectBlocks::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->sentence(5),
        ... //All other fields comes here  
    ];
});

And for Project Units :

$factory->define(App\ProjectUnits::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->sentence(5),
        ...//Other fields              
    ];
});

Now When I try to seed the above tables I am getting errors :

This is the code to seed the table:

use Illuminate\Database\Seeder;
class ProjectsTableSeeder extends Seeder
{
    public function run()
    {    
        factory(App\Projects::class, 20)->create()->each(function($u) {             
            $u->projectblocks()->save(factory(App\ProjectBlocks::class)->make()->each(function($v) {                
                $v->projectunits()->save(factory(App\ProjectUnits::class)->create());               
            })
            );//This is line number XXXXXX          
        });
    }
}

I am getting the following error:

[Symfony\Component\Debug\Exception\FatalThrowableError]
Type error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\Has
OneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model
, boolean given, called in /var/www/html/seederExample/database/seeds/Proje
ctsTableSeeder.php on line XXXXXX

Please Help me to know where I am making a mistake/s.

In case if more code is needed then please comment so that I can add the code.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire