rakete
rakete

Reputation: 3041

Add an additional field to a query

I have two tables (n:m) connected by a pivot table like this:

recipes (id, name)

user (id, playerId)

recipe_user (recipeId, userId)

At the moment I fetch the data from my mobile app like /api/v1/recipes and get a list of all recipes.

Now I want to add a scope, where I can pass the Player-ID of the app user (passed through header-data of the API request) and add a is_bookmarked field to the result of the query. At the end it should be something like this:

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

How can I "inject" this additional select to my query?

At the moment the query could be quite simple: Recipe::get()

Upvotes: 2

Views: 788

Answers (3)

tooleks
tooleks

Reputation: 585

You should join tables first and then add is_bookmarked column manually to the query. Here is an example based on the information that you have provided.

$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();

Upvotes: 1

Raza Mehdi
Raza Mehdi

Reputation: 941

Assuming each instance of Recipe you get is a collection, you can add the is_bookmarked column by:

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

    return $bookmark;
});

Upvotes: 0

moon cheese
moon cheese

Reputation: 471

assuming its an arbitrary value; for eloquent you can add the attribute directly to the model instance like such:

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

Upvotes: 0

Related Questions