简体   繁体   English

Laravel:如何使用外键插入数据

[英]Laravel: how to insert data with foreign key

I'm having trouble with the foreign key.我的外键有问题。 I have two tables.我有两张桌子。 users table and user_address table.用户表和用户地址表。 I'll show you the migration.我会告诉你迁移。

users table:用户表:

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('username')->unique()->nullable();
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

and this is the user_address table:这是 user_address 表:

public function up()
    {
        Schema::create('user_address', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->integer('mobile_no')->nullable();
            $table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
            $table->string('address')->nullable();
            $table->string('street')->nullable();
            $table->string('city')->nullable();
            $table->string('state')->nullable();
            $table->timestamps();
        });
    }

I don't know what to add or to insert in controllers / models / web routes.我不知道在控制器/模型/网络路由中添加或插入什么。 :( please help me out. :(请帮帮我。

I have Models for users and user_address users model:我有用户模型和 user_address 用户模型:

class User extends Authenticatable
{
    use HasFactory, Notifiable;
    protected $fillable = [
        'name',
        'username',
        'email',
        'password',
        'role_name',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function setUsernameAttribute($value) {
        if ( empty($value) ) {
        $this->attributes['username'] = NULL;
        } else {
            $this->attributes['username'] = $value;
        }
    }

and the user_address table:和 user_address 表:

class User_Address extends Model
{
    use HasFactory;

    protected $fillable = [
        'mobile_no',
        'shipping_address',
        'barangay',
        'city',
        'province',
    ];
}

Maybe try something like that:也许尝试这样的事情:

$user_post=request()->get('name','username','email');
$address_post=request()->get('street','city','address')

$user = new User();
$user -> fill($user_post];
$user->save();


$id=$user->id;

$address_post['user_id']=$id;
$address = new UserAdress();
$address -> fill($user_address);
$address -> save();

I don't remember now if it should be fill() or insert().我现在不记得它应该是 fill() 还是 insert()。

I would suggest creating a relationship in the User model to start with我建议在 User 模型中创建一个关系开始

public function address() {
    return $this->hasOne(Addres::class, 'user_id);
}

you can probably get away by doing你可能可以通过这样做来逃脱

tap(
   User::create(request()->get('name','username','email')), 
   fn($user)=> $user->address()
             ->save(request()->get('street','city','address')
)

Or without relationship, you will have to do something like或者没有关系,你将不得不做类似的事情

tap(
   User::create(request()->get('name','username','email')), 
   fn($user)=> Address::create[array_merge(
             ['user_id' => $user->id], 
             request()->get('street','city','address')
           )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM