gpt4 book ai didi

laravel - 保存一对一的关系。两个表中的外键

转载 作者:行者123 更新时间:2023-12-02 08:27:28 25 4
gpt4 key购买 nike

我有如下两个表:

CREATE TABLE pets(
id int NOT NULL AUTO_INCREMENT,
user_id int,
any_data varchar(255),
foreign key (user_id) references users(id),
primary key(`id`)
);

CREATE TABLE users(
id int NOT NULL AUTO_INCREMENT,
pet_id int,
any_data varchar(255),
foreign key (pet_id) references pets(id),
primary key(`id`)
);

我的模型有下一个:

用户:

public function relatedPet() {
return $this->hasOne("Pet", "pet_id");
}

宠物:

public function relatedUser() {
return $this->belongsTo("User", "user_id ");
}

我想保存一个用户并关联一个现有的宠物,但我不知道该怎么做:

$user= new User(array("any_data"=>"Hi, this is a test"));
$pet = Pet::find(1);

如何创建两个对象之间的关系?

最佳答案

首先,您的用户表不需要 pet_id。算了吧。然后

用户模型

public function pet()
{
return $this->hasOne('App\Pet'); // Changed form hasMany to hasOne
}

宠物模型

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

现在创建一个新的用户

$user = \App\User::create($data); // You need to set $fillable property
$pet = \App\Pet::findOrfail($id)
$pet->user()->associate($user);
$pet->save();

例子:

$user = \App\User::findOrFail($id);
$pet = $user->pet

// Inserting a new user and a pet
$anotherUser = \App\User::create($data);
$anotherPet = new \App\Pet($data);
$anotherUser->pet()->save($anotherPet);

$pet = \App\Pet::findOrFail($id);
$user = $pet->user

// Inserting a new pet, a user and then associating them
$anotherPet = \App\Pet::create($data);
$anotherUser = \App\User::create($data);
$anotherPet->user()->associate($anotherUser);
$anotherPet->save()

关于laravel - 保存一对一的关系。两个表中的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30761846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com