HasMany关系(或任何关系)数据已插入但未同时返回| Laravel |口才模型

时间:2019-03-06 11:04:30

标签: laravel laravel-5 eloquent

我有一个laravel应用程序,其中setting_types和用户设置保存到不同的模型中。

User.php

/*
 * Getting the user's notification setting.
*/
public function notificationSetting()
{
    return $this->hasMany('App\NotificationSetting');
}

/*
 * Controller function to get the user's settings
*/
public function getSetting(Request $request)
{
    $userSetting = $user->notificationSetting;
    // check new settings are inserted for user or not.
    if (someCondition) {
        // add new settings for user.
        $user->notificationSetting()->save(new NotificationSetting(['user_id' => $user_id, "notification_type_id" => 121]));
        print_r($user->notificationSetting); // still rec. Old values.
    }
    return $user->notificationSetting;
}

如您所见,我插入了关系对象,但没有同时收到。并且如果我再次点击(这次我的someCondition变为false),那么它将返回更新记录。

1 个答案:

答案 0 :(得分:0)

由于save()方法返回一个布尔值,因此您可以这样编写:

$user->notificationSetting()
    ->save(
        $notificationSetting = new NotificationSetting([
            'user_id' => $user_id, 
            'notification_type_id' => 121
        ])
    );

return $notificationSetting;

您也许还可以使用create()方法,该方法将返回模型的实例,但前提是这些属性当然是可填充的。

如果您想随时检索模型的所有相关记录,则可以使用如下的load()方法:

$user->load('notificationSetting');

对于hasMany关系使用复数形式也很重要,以便将其与hasOnebelongsTo关系区分:

public function notificationSettings()
{
    return $this->hasMany('App\NotificationSetting');
}