如何将一对多关系保存到数据库

时间:2017-03-03 07:23:38

标签: laravel-5 orm one-to-many

以下是我的LevelOneModel。我似乎无法弄清楚我没有包括什么。我需要帮助。

我想要实现的是在levelone表中拥有所有用户ID

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;


class LevelOneModel extends Model
{
public function users(){
    return $this->hasMany('App\User');
}

}

以下是我的用户模型

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;


class User extends Authenticatable
{
use Notifiable;

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'first_name', 
    'last_name', 
    'email',
    'phone',
    'bank_name',
    'acct_name',
    'acct_number',
    'profile_pix',
    'sme',
    'other_sme',
    'password',
];

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

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token',
];
}

以下是我的第一级迁移文件

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateLevelOneTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('level_one', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('users_id')->unsigned();
        $table->integer('upline_id')->nullable();
        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('level_one');
}
}

由于

1 个答案:

答案 0 :(得分:0)

我注意到代码中的一些内容......

看着你的课程,我理解这种关系是这样的

  • 用户只属于一个LevelOne。
  • 一个LevelOne可以有多个用户

如果这是正确的,则在迁移中错误地构建关系。因为您要将user_id添加到level_one表。

它应该是相反的:用户表必须包含level_one_id。

您应该在用户迁移中添加它,例如:

$table->int('level_one_id');
$table->foreign('level_one_id')->references('id')->on('level_one');

现在您(在数据库中)有User和LevelOne之间的连接。

现在,如果您在代码中查询用户,您也应该能够获得LevelOne内容。确保真正阅读关于人际关系的官方Laravel文档!它将为您提供实例帮助。

相关问题