我有 2 个模型,一个用户和一个地址。自从我在 https://laravel.com/docs/5.6/eloquent-relationships#updating-belongs-to-relationships 中阅读它以来,我仍在试验 associate()但我在实现它时遇到了一些麻烦,遗憾的是我的视频教程没有涵盖 associate() 函数。
class User extends Authenticatable
public function address() {
return $this->hasOne('App\Address');
}
class Address extends Model
public function user() {
return $this->belongsTo('App\User');
}
// --web.php--
Route::get('/sample',function(){
$user = User::create(['name'=>'user 1','email'=>'user@laravel.com',password='']);
$address = Address::create(['name'=>'sample address of user 1']);
$address->user()->associate($user);
});
一切都已保存,但我期望地址的 user_id 为 1。相反,地址的 user_id 被设置为 NULL。 associate() 是否应该通过自动分配等于父 ID 的外键来将特定的“belongsTo”模型链接到其父模型?顺便说一句,我对 PHP 和 Laravel 很陌生,所以是的..
最佳答案
您仍然需要保存
对象来存储值。
作为documentation说:
Belongs To Relationships
When updating a belongsTo relationship, you may use the associate method. This method will set the foreign key on the child model:
$account = App\Account::find(10); $user->account()->associate($account); $user->save();
因此,如您所见,关联后:
$address->user()->associate($user);
你需要保存它:
$address->save();
关于php - 在 Laravel 中关联(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49724941/