【问题标题】:Laravel 5 - Many to Many relationship with fieldLaravel 5 - 与字段的多对多关系
【发布时间】:2015-05-22 14:36:57
【问题描述】:

我有这种情况: 学生们 [ ID 姓名 …… ]

主题 [ ID 姓名 …… ]

Topics_got [ 学生卡 topic_id 投票 ]

我知道如何在 Laravel 5 中对其建模,但我不知道如何在 Topics_got 中插入新条目或检索数据,例如“投票”。 我怎样才能做到?

【问题讨论】:

  • 你可以试试这个。 $topic->students()->attach($id_student, ['vote' => $value]); ?
  • 是的,它适用于创建数据透视条目,但更新呢?
  • 关于获得价值?

标签: many-to-many eloquent laravel-5


【解决方案1】:

您必须访问数据透视表 (Topics_got) 才能获取或更新“投票”的值。

按照 ChainLists 的评论,你可以这样做:

将学生附加到某个主题

$topic->students()->attach($student_id, ['vote' => $value]);

获得投票的价值

// For a single student
$vote = $topic->students()->first()->pivot->vote; // Replace first() with your custom query

// Looping over all students
foreach($topic->students()->get() as $student)
{
    echo $student->pivot->vote;
}

更新投票值

$student = $topic->students()->first();
$student->pivot->vote = $newValue;
$student->pivot->save();

【讨论】:

  • 我这样做了:App\Student::find(3)->topics()->first()->pivot->vote,即使 3 是对数据库中存在枢轴和投票中的学生。
  • 也许我必须做一种数据透视表模型? (在示例 Topics_got 中)
  • 我可以设置和更新,但我无法从数据库中读取值
猜你喜欢
  • 1970-01-01
  • 2020-01-09
  • 2016-12-20
  • 1970-01-01
  • 1970-01-01
  • 2017-06-21
  • 2018-03-16
  • 2017-11-22
  • 2016-11-19
相关资源
最近更新 更多