【问题标题】:Pass Eloquent pivot value to Laravel API resource将 Eloquent 枢轴值传递给 Laravel API 资源
【发布时间】:2019-08-25 01:29:38
【问题描述】:

Laravel 5.7。我有 2 个 Eloquent 模型:所有者、猫。

所有者模型:

public function cats()
{
    return $this->belongsToMany('App\Cat')->withPivot('borrowed');
}

猫模型:

public function owners()
{
    return $this->belongsToMany('App\Owner')->withPivot('borrowed');
}

cat_owner 数据透视表具有以下字段:

id | cat_id | owner_id | borrowed
---------------------------------
1  |   3    |   2      |   1

我希望我的 API 返回所有猫的列表,如果登录用户借用了这只猫,我希望将 borrowed 字段设置为 true。这是我目前所拥有的:

控制器:

public function index()
{
    return CatResource::collection(Cat::all());
}

猫资源:

public function toArray()
{
    $data = ['id' => $this->id, 'borrowed' => false];
    $owner = auth()->user();
    $ownerCat = $owner->cats()->where('cat_id', $this->id)->first();
    if ($ownerCat) {
        $data['borrowed'] = $ownerCat->pivot->borrowed == 1 ? true : false;
    }
    return $data;
}

这可行,但为每只猫请求$owner 似乎很浪费,例如如果数据库中有 5000 只猫。有没有更有效的方法来做到这一点?我可以想到两种可能的方法:

  1. $owner 传递给CatResource(需要覆盖现有的集合资源)。

  2. 首先在控制器中获取此信息,然后再传递给CatResource

我更喜欢第二种方式,但不知道该怎么做。

【问题讨论】:

  • 如果没有猫和登录所有者的数据透视记录,结果不应该包含borrowed 字段?

标签: php laravel api eloquent pivot-table


【解决方案1】:

试试Conditional Relationship

public function toArray($request)
{
    return [
      'id' => $this->id,
      'borrowed' => false,
      'borrowed' => $this->whenPivotLoaded('cat_owner', function () {
         return $this->owner_id === auth()->id() && $this->pivot->borrowed == 1 ? true : false;
      })
   ];
}

然后拨打return CatResource::collection(Cat::with('owners')->get());

【讨论】:

  • 没有逻辑来比较猫主人和登录的主人。
  • 感谢您的坚持。不幸的是,borrowed 密钥未交付。我猜whenPivotLoading 正在返回false。我正在使用with('owners'),所以我不确定这里出了什么问题。
猜你喜欢
  • 1970-01-01
  • 2021-12-28
  • 1970-01-01
  • 2018-08-05
  • 1970-01-01
  • 1970-01-01
  • 2019-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多