Laravel 多对多只从关系中获取一个值

Laravel many to many grab only one value from relation

我在 ExpenseTag 之间有一个多对多的关系。现在我只想从与 Expense.

相关的所有标签中获取 name

所以,假设我有一个 Expense:

$expense = Expense::first();

现在我可以轻松抓取所有标签了:

$tags = $expense->tags;

这会给我一组标签。理想情况下,我想要一个标签名称数组:

array:5 [▼
  0 => "tag1"
  1 => " tag2"
  2 => " tag3"
  3 => " tag4"
  4 => " tag5"
]

现在我可以通过这样做来完成:

$tags = $expense->tags;

$new_tags = [];

foreach($tags as $tag)
{
    $new_tags[] = $tag->name;
}

但是有没有更简洁的方法,尤其是不必使用 foreach?我试过这样的事情:

$tags = $expense->tags->value('name')->toArray();

$tags = $expense->tags()->value('name')->toArray();

但是两者都不起作用。有没有办法让这个工作?

试试这个

$tags = $expense->tags->pluck('name')->toArray();

$tags = $expense->tags->pluck('name')->all();

这就是你要找的吗?

$tags = $expense->tags->pluck('name');

您可以在这里进一步阅读: https://laravel.com/docs/5.6/collections#method-pluck