php - 在 Laravel 中关联()

标签 php laravel eloquent associate

我有 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/

相关文章:

php - Yii2 AccessControl 在 Rest API 中使用 HTTPBearerAuth 时给出 Forbidden 403

php - Zend_Db : Filter results

linux - Composer 更新不运行

php - wamp/ Composer /laravel5 : localhost:8000 just stopped working for no reason

php - 在 Laravel/Eloquent 中对类似的通知进行分组

Laravel Eloquent : Rename fields only in Model Class

php - 如何在 Laravel 6 中的文件夹和数据库中删除 1 周后的文件?

javascript - 删除 Dropzone.js 和 PHP 不起作用的脚本

javascript - React - 期望进行赋值或函数调用,但却看到表达式无法编译

Laravel 4 Eloquent ORM : How to update a pivot table entry that has composite primary keys