【问题标题】:How to get data with pivot data attached?如何获取附加数据透视表的数据?
【发布时间】:2019-10-11 17:09:27
【问题描述】:

我正在尝试从我的 Lists 表中获取数据,并包含一个包含该列表中曲目 ID 的数组。

这是一个数据库模型示例,具有关系 N:M。

在我的 List 模型中,我添加了这个方法:

public function tracks()
{
   return $this->belongsToMany(Track::class, 'List_Tracks', 'id_list', 'id_track');
}

所以,在我的 ListController 中,我正在执行以下操作:

$list = List::find($id);
$list->tracks_list = $list->tracks->pluck('track_id');
return $list;

我得到的是与我在同一个列表中的曲目一样多的对象,例如:

[
{
 "id_track": 1,
 "name": "Yesterday",
 "tracks_list": [
  1,
  2
 ]
 "pivot": {
    "id_list": 1,
    "id_track": 1
 }
},
{
 "id_track": 2,
 "name": "Lucy in the sky with diamonds",
 "pivot": {
    "id_list": 1,
    "id_track": 2
 }
}
]

但我想得到的是:

{
 "id_list": 1,
 "name": "The Best of The Beatles",
 "tracks_list": [
  1,
  2
]
}

我认为我尝试过的事情比正确的解决方案要复杂得多。

您将如何以这种方式获取数据?

提前致谢。

【问题讨论】:

  • 你试过List::find($id)->with('tracks');吗?我认为应该从关系而不是数据透视表中获取数据。您可能需要稍微更改调用 = List::with('tracks')->where('id', '=', $id)->first()
  • @Silencesys 没错,它带来了整个对象,这让我觉得也许我只需要数组中的 ID,例如:{“id_list”:1,“name”:“ The Best of The Beatles", "tracks": [ 1, 2 ] } Laravel 有什么方法可以轻松做到这一点?

标签: php laravel


【解决方案1】:

您需要先加载关系,然后编写 eloquent 查询的其余部分,否则您将只能从数据透视表中获取 id 列表。

List::with('tracks')->where('id', '=', $id)->first();
// Following method should work too
List::with('tracks')->find($id);


根据您的评论 - 只获取与列表相关的 id 数组,您不需要加载关系并且只能使用:

List::find($id)->tracks()->pluck('id');
// In case previous method will not work, you can try this one:
List::find($id)->tracks()->pluck('tracks.id');
// before dot should be name of the table, not relationship's.

因此,如果您只需要附加到播放列表的曲目的 ID。我建议将以下方法添加到您的 List 模型中:

// App\Models\List
public function getTrackIdsAttribute()
{
    return $this->tracks->pluck('id')->toArray();
}

然后您应该能够简单地调用List::find($id)->trackIds 来获取附加到给定列表的所有曲目ID。如果您不确定我为什么将方法定义为 getTrackIdsAttribute 并仅在模型上调用 trackIds,请查看 Eloquent: Mutators

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-25
    • 1970-01-01
    • 2018-06-08
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    • 2015-12-11
    相关资源
    最近更新 更多