【问题标题】:Get back data from the pivot table when store a many-to-many relationship存储多对多关系时从数据透视表中取回数据
【发布时间】:2018-06-23 23:45:58
【问题描述】:

我在项目和调查之间存在多对多关系。我可以成功地在调查和项目之间建立关系

$userSurvey = $project->surveys()->save($survey);。

这将在question_survey 数据透视表内创建一条新记录(数据透视表包含id、question_id 和survey_id 列。)

$userSurvey 将收到新创建的调查模型。有什么方法可以同时接收question_survey 数据透视表中新记录的id?

【问题讨论】:

    标签: laravel eloquent laravel-eloquent


    【解决方案1】:

    当检索 多对多 关系时,Laravel 会自动将 pivot 附加到生成的 Model,所以在你的情况下,$userSurvey将自动拥有一个名为pivot 的属性,当然,它包含枢轴。

    但默认情况下,pivot 属性仅包含 外键,因此在您的情况下,question_id 和 survey_id。如果您有任何其他额外属性(在您的情况下为id),只需使用withPivot 方法,如下所示。

    public function surveys()
    {
        return $this->belongsToMany('App\Question', 'question_survey')
                    ->withPivot('id');
    }
    

    现在您可以从数据透视表访问id:

    $userSurvey->pivot->id;
    

    奖励,如果您认为 pivot 字不符合您的措辞风格,只需在您的关系中使用 as 方法来自定义 pivot 的变量名属性。

    public function surveys()
    {
        return $this->belongsToMany('App\Question', 'question_survey')
                    ->as('question_survey')
                    ->withPivot('id');
    }
    

    现在您可以从数据透视表访问id:

    $userSurvey->question_survey->id;
    

    【讨论】:

      猜你喜欢
      • 2020-07-03
      • 1970-01-01
      • 2021-05-31
      • 2018-09-15
      • 1970-01-01
      • 2018-03-20
      • 1970-01-01
      • 1970-01-01
      • 2023-02-05
      相关资源
      最近更新 更多