向查询添加附加字段

Add an additional field to a query

我有两个 tables (n:m) 通过枢轴 table 连接,如下所示:

食谱 (id, name)

用户 (id, playerId)

recipe_user (recipeId, userId)

目前我从我的移动应用程序中获取数据,例如 /api/v1/recipes 并获取所有食谱的列表。

现在我想添加一个范围,我可以在其中传递应用程序用户的 Player-ID(通过 API 请求的 header-data 传递)并添加一个 is_bookmarked 字段添加到查询结果中。最后它应该是这样的:

[
 {
  "id": 1,
  "name": "Pizza",
  "is_bookmarked": 1 
 },
 {
  "id": 1,
  "name": "Pizza",
  "is_bookmarked": 1 
 }
]

如何 "inject" 这个额外的 select 到我的查询?

目前查询可能非常简单:Recipe::get()

假设它是一个任意值;对于 eloquent,您可以像这样将属性直接添加到模型实例:

 $temp = App\Recipe::first();
 $temp->is_bookmarked = 1;
 return $temp;

假设您获得的每个 Recipe 实例都是一个集合,您可以通过以下方式添加 is_bookmarked 列:

$bookmark = $request->hasHeader('user_id');
$data = $recipes->map(function($recipe) use($bookmark) {
    if ($bookmark === true) {
       $bookmark->push(['is_bookmarked' => 1]);
    }

    return $bookmark;
});

您应该先连接表,然后手动将 is_bookmarked 列添加到查询中。这是一个基于您提供的信息的示例。

$userId = 1; // Get an app user id.

$recipes = Recipe::select('recipes.*')
    ->leftJoin('recipe_user', function ($join) use ($userId) {
        return $join
            ->on('recipe_user.recipeId', '=', 'recipes.id')
            ->on('recipe_user.userId', '=', DB::raw($userId));
    })
    ->addSelect(DB::raw('recipe_user.recipeId AS is_bookmarked'))
    ->get();