2

我正在尝试将数据透视数据返回到资源。数据透视表有效,我可以添加和删除预期的条目,但我无法获得 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。

4

1 回答 1

2

->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',
}
于 2020-02-12T21:20:48.213 回答