Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel use with() , pluck() together

Tags:

php

laravel

Query Output

\App\Post :

function PostMeta(){
    return $this->hasMany('App\PostMeta');
}

And my Query : ( pluck is not working) -

I need to use less database queries

$query = \App\Post
      ::with(array('PostMeta'=>function($query){
          $query->pluck('key','value');
      }));
       $query->get();

I need to get title_en , But I cant use pluck here!

New Update

solved:

function get_PostMeta(){
      // print_r($this->relations['PostMeta']);
      return $this->relations['PostMeta'];
    }


$query = \App\Post::with('PostMeta')->get();
      foreach ($query as $key => $post){
        $post->meta = $post->get_PostMeta()->pluck('value', 'key');
      }
like image 335
danial dezfooli Avatar asked Apr 23 '17 11:04

danial dezfooli


People also ask

What is Pluck () in Laravel?

Laravel Pluck() is a Laravel Collections method used to extract certain values from the collection. You might often would want to extract certain data from the collection i.e Eloquent collection.

What is difference between Pluck and select in Laravel?

Pluck function normally used to pull a single column from the collection or with 2 columns as key, value pairs, which is always be a single dimension array. Select will return all of the columns you specified for an entity in a 2 dimensional array, like array of selected values in an array.

What is the difference between Pluck and select?

The select Method is another way to limit the fields selected from your database. The main difference to pluck is that an ActiveRecord model object is created, instead of returning an array of the selected fields. This allows you to call methods on this model. >

What does get () do in Laravel?

This allows you to add conditions throughout your code until you actually want to fetch them, and then you would call the get() function.


1 Answers

You can't do this while eager loading the data, but you can use collection method with the same name pluck() in the view when accessing the relation data:

{{ $post->postMeta->pluck('value', 'key') }}

In this case, you'll avoid N+1 problem and get data in the format you want.

Update

Since you want to prepare data for Vue, here's a small example of how you could iterate over the collection:

foreach ($posts as $post) {
    $post->meta = $post->postMeta->pluck('value', 'key');
    unset($post->postMeta);
}
like image 142
Alexey Mezenin Avatar answered Oct 05 '22 02:10

Alexey Mezenin