Я иметь модель Account, которая имеет как user() (один-ко-многим), так и superUser() (один-к-одному), оба из которых хранятся во встроенном -в модели User. Как и в случае обычных связей «один ко многим», таблица «многие» (
Код: Выделить всё
usersАккаунты:
Код: Выделить всё
/* model */
public function superUser()
{
return $this->hasOne(User::class, 'id', 'superuser_id');
}
public function users()
{
return $this->hasMany(User::class);
}
/* migration */
public function up()
{
Schema::create('accounts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('superuser_id')->unsigned();
$table->string('name');
$table->timestamps();
$table->foreign('superuser_id')
->references('id')
->on('users')
->onDelete('cascade');
});
}
Код: Выделить всё
/* model */
public function account()
{
return $this->belongsTo(Account::class);
}
/* migration */
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('account_id')->unsigned()->index()->nullable();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Создайте пользователя:
< pre class="lang-php Prettyprint-override">
Код: Выделить всё
>>> $user = factory(App\User::class)->create()
=> App\User {#3014
name: "Rose Grant II",
email: "ernser.thomas@example.com",
email_verified_at: "2019-05-31 15:38:32",
updated_at: "2019-05-31 15:38:32",
created_at: "2019-05-31 15:38:32",
id: 23,
}
Код: Выделить всё
>>> $account = factory(App\Account::class)->create(['superuser_id' => $user]);
=> App\Account {#3024
name: "Kuhic-Price",
superuser_id: 23,
updated_at: "2019-05-31 15:39:11",
created_at: "2019-05-31 15:39:11",
id: 17,
}
>>> $account->superUser
=> App\User {#3011
id: 23,
account_id: null,
name: "Rose Grant II",
email: "ernser.thomas@example.com",
email_verified_at: "2019-05-31 15:38:32",
api_token: null,
created_at: "2019-05-31 15:38:32",
updated_at: "2019-05-31 15:38:32",
}
Код: Выделить всё
account_idКод: Выделить всё
>>> $account->superUser->account()->associate($account)->save()
=> true
>>> $account->superUser
=> App\User {#3011
id: 23,
account_id: 17,
name: "Rose Grant II",
email: "ernser.thomas@example.com",
email_verified_at: "2019-05-31 15:38:32",
api_token: null,
created_at: "2019-05-31 15:38:32",
updated_at: "2019-05-31 15:43:55",
account: App\Account {#3024
name: "Kuhic-Price",
superuser_id: 23,
updated_at: "2019-05-31 15:39:11",
created_at: "2019-05-31 15:39:11",
id: 17,
superUser: App\User {#3011},
},
}
Код: Выделить всё
>>> $account->toArray()
^C
Подробнее здесь: https://stackoverflow.com/questions/563 ... ve-toarray
Мобильная версия