【问题标题】:laravel pivot table get wrong recordslaravel 数据透视表得到错误的记录
【发布时间】:2017-11-14 14:23:09
【问题描述】:

这是“评估”表

-id
-title
-slug

这是“成员”表

-id
-name
-surname

这是“evalution_member”数据透视表

-evalution_id
-member_id

评估表有3条记录如下

id | title | slug
1 | a | a
2 | b | b
3 | c | c

成员表有10条记录如下

id | name | surname
1 | xx1 | xx1
2 | xx2 | xx2
3 | xx3 | xx3
4 | xx4 | xx4
5 | xx5 | xx5
6 | xx6 | xx6
7 | xx7 | xx7
8 | xx8 | xx8
9 | xx9 | xx9
10 | xx10 | xx10

evalution_member 表有 10 条记录如下

evalution_id |member_id
1 | 1
1 | 2
1 | 3
3 | 4
3 | 5
3 | 6
3 | 7
3 | 8
3 | 9
3 | 10

这是我的评估模型

public function members()
{
    return $this->belongsToMany('App\Member');
}

这是我的会员模型

public function evalutions()
{
    return $this->belongsToMany('App\Evalution');
}

这是我的代码:

$evalution = Evalution::find($id)->with('members')->first();

从此代码返回成员列表但出现错误记录。正确的记录必须从第 4 项开始,到最后一项结束,但返回列表包含前 3 条记录。

如果我改变评估模型如下:

public function members()
{
    return $this->belongsToMany('App\Http\Models\Member', 'evalution_member', 'evalution_id', 'member_id');
}

返回列表仅包含 1 条记录,它是 evalution_member 表上的最后一条记录。

为什么?

那里有什么问题?

【问题讨论】:

  • 你确定你发送的是正确的$id
  • 我会再次检查,但我确定正确的 id

标签: php mysql laravel pivot-table laravel-5.4


【解决方案1】:

将数据透视表名称添加到这样的方法中。

public function members()
{
    return $this->belongsToMany('App\Member', 'evalution_member');
}

【讨论】:

  • 我像这样更改控制器代码:$evalution = Evalution::with('members')->find($id);它有效...
猜你喜欢
  • 2014-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-10
  • 2019-08-19
  • 2018-12-22
  • 2015-04-01
  • 2019-04-27
相关资源
最近更新 更多