【问题标题】:Laravel Eloquent ID as array keyLaravel Eloquent ID 作为数组键
【发布时间】:2018-10-21 12:07:20
【问题描述】:

在我的控制器类中,我正在获取属于当前登录用户的所有餐厅特色菜,以及特色菜的美食类型以及特色菜所属的餐厅。

我使用下面的sn-p:

public function edit(Special $special)
{
   dd($special->with('restaurants')->with('cuisines')->get()->keyBy('id')->toArray());
}

这会产生:

->keyBy('id') 方法允许我将“特殊”数组键设置为数据库中的记录 ID。

但是,我不知道如何将关系记录数组键设置为它们各自的 ID。

例如。 餐厅数组中的第一项应具有“1”键。美食数组中的第一项应具有“25”键。

我尝试过这样的事情:

$special->with('restaurants')->keyBy('id')->with('cuisines')->keyBy('id')->get()->keyBy('id')->toArray()

抛出: 方法 Illuminate\Database\Query\Builder::keyBy 不存在。

我的美食和餐厅表都有一个主键 id 列。

【问题讨论】:

  • keyBy(...) 是收集功能,因此您需要在每个关系上“链接”此调用。我不打算在这里写整个链,但想法是 $special->with(['restaurants', 'cuisines'])->get()->keyBy('id')->first()->restaurants->keyBy('id')... 关键是这仅适用于 first $special 所以你需要使用 transform() 或 @987654324 @.
  • 您能否就答案提供反馈?

标签: php laravel eloquent many-to-many relationship


【解决方案1】:

使用这个:

$special->with($relations = ['restaurants', 'cuisines'])->get()->keyBy('id')
    ->each(function($special) use($relations) {
        foreach($relations as $relation) {
            $special->setRelation($relation, $special->$relation->keyBy('id'));        
        }
    });

【讨论】:

    【解决方案2】:

    这应该可以解决问题:

    $result = $special->with(['restaurants', 'cuisines'])->get()->keyBy('id')->map(function ($item) {
        $item->restaurants->keyBy('id');
        $item->cuisines->keyBy('id');
    
        return $item;
    });
    

    或者稍微好一点的版本:

    $result = $special->with(['restaurants', 'cuisines'])->get()->keyBy('id')->map(function ($item) {
        foreach (array_keys($item->getRelations()) as $relation) {
            if ($item->relationLoaded($relation)) {
                $item->$relation->keyBy('id');
            }
        }
    
        return $item;
    });
    

    【讨论】:

      【解决方案3】:
       $result = $special->with(['restaurants', 'cuisines'])->get()
              ->keyBy('id')
              ->map(function ($item) {
              $item->restaurants->keyBy('id');
              $item->cuisines->keyBy('id');
              return $item;
          });
      

      【讨论】:

      • @kyslik 差不多了。
      • 是的,我在那里 :)
      • 你需要返回$item
      猜你喜欢
      • 2015-01-08
      • 2021-08-28
      • 2021-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多