gpt4 book ai didi

php - 尝试在资源 Laravel 中返​​回数据透视表

转载 作者:行者123 更新时间:2023-12-04 10:35:43 24 4
gpt4 key购买 nike

我正在尝试将数据透视数据返回到资源。
数据透视表有效,我可以像预期的那样添加和删除条目,但我无法获得 ActivityResource 中返回的 user_id ...
在 Laravel 文档中看起来很简单,我错过了什么吗?

// Activity.php
class Activity extends Model
{
public function members()
{
return $this->belongsToMany('App\User', 'activity_user', 'user_id', 'activity_id')->withPivot('activity_id','user_id')->withTimestamps();
}
}

// User.php
class User extends Authenticatable
{
public function joinedactivities()
{
return $this->belongsToMany('App\Activity');
}
}

在我的 ActivityController 中,我想返回一个新创建的具有“热切加载”关系的 ActivityResource

// ActivityController 
public function show($id)
{
$activity = Activity::with('members')->findOrFail($id);

/* foreach ($activity->members as $user) {
echo $user->id . " "; // With this I can actually see the right ids
}
return;*/

return new ActivityResource($activity);
}

事件资​​源:
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'attendees' => $this->whenPivotLoaded('activity_user', function () {
return $this->pivot->user_id;
}),
];
}

我没有收到任何错误,而是没有返回与会者字段。我尝试了很多东西,为此而挣扎。非常感谢帮助。
我正在使用 Laravel 6。

最佳答案

->withPivot('activity_id','user_id')不需要。无论如何,这些字段都会出现在您的关系对象上。对于资源,我认为您可以执行以下操作:

public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
// If the relation 'members' is loaded, get an array of user ids otherwise, return null
'attendees' => $this->relationLoaded('members') ? $this->members->pluck('pivot.user_id')->unique()->all() : null
];
}

主要问题是这种关系是多对多的,这意味着有多个枢轴。使用此解决方案,您的对象将如下所示。
{
id: 3,
title: 'A Title',
attendees: [
1,
2,
3,
],
}

如果您希望将 id 连接到单个字符串中,例如您评论的 foreach , 替换 all()来自 join(' ')
// If the relation 'members' is loaded, get an string of user ids otherwise, return null
'attendees' => $this->relationLoaded('members') ? $this->members->pluck('pivot.user_id')->unique()->join(' ') : null
{
id: 3,
title: 'A Title',
attendees: '1 2 3',
}

关于php - 尝试在资源 Laravel 中返​​回数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60193718/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com