从belongsToMany 关系中获取相关ID 数组 - Laravel 5.4

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42053194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:16:40  来源:igfitidea点击:

Getting array of related IDs from a belongsToMany relation - Laravel 5.4

phplaravellaravel-5laravel-5.4

提问by Peter

I had thissolution working well in Laravel 5.3

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

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

In my Proceduremodel:

在我的Procedure模型中:

public function stages()
{

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

Now, after migrating to Laravel 5.4, I get this error:

现在,迁移到 Laravel 5.4 后,我收到此错误:

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

Seems that the getRelatedIdshas been removed.

好像getRelatedIds已经删除了。

My question:

我的问题:

how to get the array in 5.4?

如何在 5.4 中获取数组?

Thank you in advance.

先感谢您。

回答by Ordidaad

to get ids array you can use pluck function

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

$procedure->stages()->pluck('stages.id')->toArray();

回答by GabMic

It was removed(basically, changed the name, nothing more) from 5.4, but you have it in another name as i looked deep inside the belongToMany.phpfile. Use this And it should work very nicely.

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

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

Hope this help you, and other who will face that problem in the future and look in this post.

希望这对您和其他将来会遇到该问题的人有所帮助,并查看这篇文章。