Кто-нибудь будет так любезен, чтобы помочь мне? Я пытаюсь (напрасно) создать отношение «многие ко многим» в laravel.
Структура базы данных выглядит хорошо для меня, но отношения не работают.
У меня есть 2 таблицы / модели users
и competencies
(один пользователь, много пользователей) (одна компетенция, много компетенций)
1. Сначала я создал миграцию базы данных:
class CreateCompetencyUserTable extends Migration
{
public function up()
{
Schema::create('competency_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('competency_id')->unsigned();
$table->foreign('competency_id')->references('id')->on('competencies');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
});
}
public function down()
{
Schema::dropIfExists('competency_user');
}
}
установка 2, связывающая модели в модели
user
, я создаю метод
competencies
, а в модели
Competency
метод
users
.
В документации ничего не говорится еще, так что это должно быть правильно?
class User extends Authenticatable
{
use HasApiTokens, Notifiable, SoftDeletes;
protected $casts = [
'created_at' => 'datetime',
'updated_at' => 'datetime',
'is_admin' => 'bool',
'is_super_admin' => 'bool'
];
protected $fillable = [
'name', 'email', 'password', 'team_id'
];
protected $hidden = [
'password', 'remember_token', 'is_admin', 'is_super_admin'
];
public function competencies()
{
return $this->belongsToMany(Competency::class,'competency_user','user_id','competency_id');
}
}
class Competency extends Model
{
use SoftDeletes;
protected $casts = [
'created_at' => 'datetime',
'updated_at' => 'datetime',
];
protected $fillable = [
'name', 'description', 'icon', 'competency_set_id', 'card_image_da_id', 'order_value'
];
public function users()
{
return $this->belongsToMany(User::class, 'competency_user', 'competency_id', 'user_id');
}
после этого, когда я запускаю
$user = User::find(1);
$user->competencies()->attach(4);
$user->save();
или
$user = User::find(1);
$competency = Competency::find(4);
$user->competencies()->attach($competency);
$user->save();
ничего .....
Я надеюсь, что любой может помочь мне, и что у меня есть достаточно информации, благодаря Максиму
редактировать:
миграция: пользователи
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->boolean('is_admin')->default(false);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
миграция компетенции
class CreateCompetenciesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('competencies', function (Blueprint $table) {
$table->increments('id');
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
$table->string('icon');
$table->string('name');
$table->mediumText('description');
$table->unsignedInteger('order_value')->default(99999);
$table->unsignedInteger('competency_set_id');
$table->foreign('competency_set_id')->references('id')->on('competency_sets');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('competencies');
}
}