6

我有这个解决方案在 Laravel 5.3 中运行良好

$procedure = Procedure::findOrFail($id);
$attached_stages = $procedure->stages()->getRelatedIds()->toArray();

在我的Procedure模型中:

public function stages()
{

    return $this->belongsToMany('App\Models\Stage', 'procedure_stage', 'procedure_id', 'stage_id')->withPivot('id','status')->withTimestamps();
}

现在,在迁移到 Laravel 5.4 后,我收到了这个错误:

Call to undefined method Illuminate\Database\Query\Builder::getRelatedIds()

似乎getRelatedIds已删除。

我的问题:

如何在 5.4 中获取数组?

先感谢您。

4

3 回答 3

14

它已从 5.4 中删除(基本上,更改了名称,仅此而已),但是当我深入查看belongToMany.php文件时,您使用了另一个名称。使用它它应该可以很好地工作。

$attached_stages = $procedure->stages()->allRelatedIds()->toArray();

希望这对您以及将来会遇到该问题并查看此帖子的其他人有所帮助。

于 2017-02-05T14:38:17.747 回答
12

要获取 ids 数组,您可以使用 pluck 函数

$procedure->stages()->pluck('stages.id')->toArray();
于 2017-02-05T14:31:57.347 回答
0

可能对 Laravel 5.1 上的用户有用:

$procedure->stages()->getQuery()->lists('stage_id')->toArray();

或者

$procedure->stages()->getQuery()->pluck('stage_id')->toArray();

它是 IDE 友好的代码版本。:)

于 2020-11-25T12:24:23.070 回答