Вызов Laravel функции-члену create () для необъекта

Я пытаюсь заполнить базу данных с использованием некоторых модельных фабрик, но получаю ошибку call to member function create() on a non-object

Ниже приведены мои модельные заводы:

$factory->define(App\Organisation::class, function ($faker) {
return [
'name' => $faker->company,
];
});

$factory->define(App\Department::class, function ($faker) {
return [
'name' => $faker->catchPhrase,
'organisation_id' => factory(App\Organisation::class)->make()->id,
];
});

$factory->define(App\User::class, function ($faker) {
return [
'email' => $faker->email,
'password' => str_random(10),
'organisation_id' => factory(App\Organisation::class)->make()->id,
'remember_token' => str_random(10),
];
});

В моем сеансе я использую следующее, чтобы создать 2 организации и связать пользователя и отдел с каждой организацией, а затем сделать пользователя руководителем этого отдела:

factory(App\Organisation::class, 2)
->create()
->each(function ($o)
{
$user = $o->users()->save(factory(App\User::class)->make());

$department = $o->departments()->save(factory(App\Department::class)->make());

$department->managedDepartment()->create([
'organisation_id' => $o->id,
'manager_id' => $user->id,
]);


});

Однако я получаю фаталеррорецепцию call to member function create() on a non-object

я думал $department такое объект?

Моя модель отдела выглядит следующим образом:

class Department extends Model
{

protected $fillable = ['name','organisation_id'];

public function organisation()
{
return $this->belongsTo('App\Organisation');
}

/* a department is managed by a user */
public function managedDepartment()
{
$this->hasOne('App\ManagedDepartment');
}
}

И моя модель управляемого отделения выглядит следующим образом:

class ManagedDepartment extends Model
{
protected $table = 'managed_departments';


protected $fillable = ['organisation_id', 'department_id', 'manager_id',];


public function department()
{
$this->belongsTo('App\Department');
}

public function manager()
{
return $this->belongsTo('App\User');
}
}

Кто-нибудь может помочь?

1

Решение

Попробуйте вернуть ваше отношение

    public function department()
{
return $this->belongsTo('App\Department');
}

И здесь

 /* a department is managed by a user */
public function managedDepartment()
{
return $this->hasOne('App\ManagedDepartment');
}

Я думаю, что это решит вашу проблему.

0

Другие решения

Во-первых, не делайте внешние ключи заполняемыми!
Во-вторых, где ваша организация функционирует в ManagedDepartment? Вы должны создать его, иначе следующее не будет работать, потому что ассоциация невозможна.
В-третьих, я думаю, что вы должны изменить make () на create () в следующем

$factory->define(App\Organisation::class, function ($faker) {
return [
'name' => $faker->company,
];
});

$factory->define(App\Department::class, function ($faker) {
return [
'name' => $faker->catchPhrase,
'organisation_id' => factory(App\Organisation::class)->create()->id,
];
});

$factory->define(App\User::class, function ($faker) {
return [
'email' => $faker->email,
'password' => str_random(10),
'organisation_id' => factory(App\Organisation::class)->create()->id,
'remember_token' => str_random(10),
];
});

Более того:

factory(App\Organisation::class, 2)
->create()
->each(function ($o)
{
$user = factory(App\User::class)->create();
$o->users()->attach($user->id);

$department = factory(App\Department::class)->create();
$o->departments()->attach($department);

$managedDep = new ManagedDepartment();
$managedDep->associate($o);
$managedDep->associate($user);
$managedDep->associate($department);
$managedDep->save();
});
0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector