Laravel Eloquent Select, где запрос возвращает пустой массив - PullRequest
0 голосов
/ 16 мая 2019

Сейчас я использую Laravel Eloquent для получения покупок из определенного пакета; предположительно, эта строка:

$customer_words_per_pack = $customer_words->where('note', 'like', $pack_title); 

должен возвращать объекты результата запроса в массиве, вместо этого он возвращает пустой массив. Тем не менее, я могу получить весь список пакетов, используя этот запрос:

$models = \App\Models\WordPack::groupBy('description')->get();

Когда я создаю запрос, который получает все выбранные пакеты покупок, используя:

$pack_title = '%'.$pack->description.'%'; 

$pack->description возвращает строку, но когда я помещаю ее в запрос, она ничего не возвращает.

Моя цель для этого - получить все покупки из этого пакета. Что может быть наиболее вероятной причиной невозвращения результатов при использовании Laravel Eloquent?

Контроллер

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class WebGetSalesReportsController extends BaseController
{
    //
    public function handle(Request $request)
    {
        $models = \App\Models\WordPack::groupBy('description')->get();

        $viewData = [ 'title' => 'Quick-E - Sales Reports',
                      'packs' => $models ];
        return view($this->getViewGroup() . 'sales_reports', $viewData);

    }


    public function generate(Request $request){
        $dateFrom = $request->input('date-from');
        $dateTo = $request->input('date-to');
        $pack_selected = $request->input('packs');
        $str_selected = '%'.$pack_selected.'%';
        $request->session()->flash('date-from', $dateFrom);
        $request->session()->flash('date-to', $dateTo);
        $request->session()->flash('packs', $pack_selected);
        $action = $request->input('action', 'Go');
        $models = \App\Models\WordPack::groupBy('description')->get();
        $price = \App\Models\WordPack::where('description', $pack_selected)->get();
        $customer_words = \App\Models\CustomerWord::select('customer_emails.first_name', 'customer_emails.last_name', 'words', 'customer_words.created_at', 'note')
                                                  ->join('customer_emails', 'customer_words.customer_id', '=', 'customer_emails.customer_id')
                                                  ->whereNotNull('verified_at');



        //var_dump($customer_words);
        if(strlen($dateFrom) == 0 && strlen($dateTo) == 0){
            if($pack_selected == 'all_packs'){
                $customer_words = $customer_words->get();
            }
            else{
                $customer_words = $customer_words->where('note', 'like', $str_selected)
                                ->get();
            }
        }
        else if(strlen($dateFrom) != 0 && strlen($dateTo) != 0){
            if($pack_selected == 'all_packs'){
                $customer_words = $customer_words->whereBetween('customer_words.created_at', [ $dateFrom , $dateTo ])
                                ->get();
            }
            else{
                $customer_words = $customer_words->where('note', 'like', $str_selected)
                                ->whereBetween('customer_words.created_at', [ $dateFrom , $dateTo ])
                                ->get();
            }
        }

        if($action === 'CSV')
            return $this->makeCsv($dateFrom, $dateTo, $pack_selected, $models, $customer_words);

        $viewData = [ 'title' => 'Quick-E - Sales Reports',
                      'packs' => $models,
                      'dateFrom' => $dateFrom,
                      'dateTo' => $dateTo,
                      'pack_selected' => $pack_selected,
                      'customer_words' => $customer_words ];
        return view($this->getViewGroup() . 'sales_reports_results', $viewData);
    }

    private function makeCsv($dateFrom, $dateTo, $pack_selected, $models, $customer_words)
    {
        $newLine = "\r\n";

        $result = ob_start();
        if($result !== true)
            die('error generating report');

        /*if by pack*/
        if($pack_selected != 'all_packs'){
            echo '"Date"';
            echo ',';
            echo '"' . date("M d, Y", strtotime($dateFrom)) ." to ". date("M d, Y", strtotime($dateTo)) . '"';
            echo $newLine;

            echo '"Pack"';
            echo ',';
            echo '"' . $pack_selected . '"';
            echo $newLine;

            echo '"No. of Packs Purchased"';
            echo ',';
            echo '"' . $customer_words->count() . '"';
            echo $newLine;

            echo '"Total Sales"';
            echo ',';

            $price_total = 0;
            foreach($customer_words as $customer_word){
                $json_note = json_decode($customer_word->note, true);
                $price_total += $json_note['price'];
            }

            echo '"$' . round($price_total, 2) . '"';
            echo $newLine;

            echo $newLine;
            echo $newLine;

            echo '"Date Purchased"';
            echo ',';

            echo '"Word Pack"';
            echo ',';

            echo '"Words"';
            echo ',';

            echo '"Price"';
            echo ',';

            echo '"Customer"';
            echo ',';

            echo $newLine;


            foreach($customer_words as $customer_word){
                $json_note = json_decode($customer_word->note, true);

                echo '"'.date("M d, Y g:i:s A", strtotime($customer_word->created_at)).'"';
                echo ',';

                echo '"'.$pack_selected.'"';
                echo ',';

                echo '"'.$customer_word->words.'"';
                echo ',';

                echo '"$'.round($json_note['price'], 2).'"';
                echo ',';

                echo '"'.$customer_word->first_name.' '.$customer_word->last_name.'"';
                echo ',';

                echo $newLine;
            }
            echo $newLine;
            echo $newLine;
        }

        /*all packs*/
        if($pack_selected != 'all_packs'){
            foreach($models as $pack){
                var_dump($pack->description);
                $pack_title = '%'.$pack->description.'%';
                $customer_words_per_pack = $customer_words->where('note', 'like', $pack_title);
                if($customer_words_per_pack->count() > 0){
                    echo '"Date"';
                    echo ',';
                    echo '"' . date("M d, Y", strtotime($dateFrom)) ." to ". date("M d, Y", strtotime($dateTo)) . '"';
                    echo $newLine;

                    echo '"Pack"';
                    echo ',';
                    echo '"' . $pack->description . '"';
                    echo $newLine;

                    echo '"No. of Packs Purchased"';
                    echo ',';
                    echo '"' . $customer_words_per_pack->count() . '"';
                    echo $newLine;

                    echo '"Total Sales"';
                    echo ',';

                    $price_total = 0;
                    foreach($customer_words_per_pack as $customer_word){
                        $json_note = json_decode($customer_word->note, true);
                        $price_total += $json_note['price'];
                    }

                    echo '"$' . round($price_total, 2) . '"';
                    echo $newLine;

                    echo $newLine;
                    echo $newLine;

                    echo '"Date Purchased"';
                    echo ',';

                    echo '"Word Pack"';
                    echo ',';

                    echo '"Words"';
                    echo ',';

                    echo '"Price"';
                    echo ',';

                    echo '"Customer"';
                    echo ',';

                    echo $newLine;


                    foreach($customer_words_per_pack as $customer_word){
                        $json_note = json_decode($customer_word->note, true);

                        echo '"'.date("M d, Y g:i:s A", strtotime($customer_word->created_at)).'"';
                        echo ',';

                        echo '"'.$pack_selected.'"';
                        echo ',';

                        echo '"'.$customer_word->words.'"';
                        echo ',';

                        echo '"$'.round($json_note['price'], 2).'"';
                        echo ',';

                        echo '"'.$customer_word->first_name.' '.$customer_word->last_name.'"';
                        echo ',';

                        echo $newLine;
                    }
                    echo $newLine;
                    echo $newLine;
                }
            }
        }

        $csv = ob_get_contents();

        $result = ob_end_clean();
        if($result !== true)
            die('error finalizing report');


        $filename = tempnam("/tmp", str_random(5) . '.sales.report');
        file_put_contents($filename, $csv);

        $headers = array(
            'Content-Type' => 'text/csv',
        );

        $pack_name = $pack_selected;
        if($pack_selected == 'all_packs')
            $pack_name = 'All Packs';

        $docName = "sales_".date("m-d-Y_h-i-s-A")."[".$pack_name."].csv";
        return \Response::download($filename, $docName, $headers);
    }
}

Посмотреть

@foreach($packs as $pack)
    <?php
        $pack_title = '%'.$pack->description.'%';
        $customer_words_per_pack = $customer_words->where('note', 'like', $pack_title);
        echo $customer_words_per_pack;
    ?>
    @if($customer_words_per_pack->count() > 0)
    <div class="box-top-info">
        <p class="top-info">Date: <?php echo date("M d, Y", strtotime($dateFrom)) ." to ". date("M d, Y", strtotime($dateTo)); ?></p>
        <p class="top-info">Pack: {{ $pack->description }}</p>
        <p class="top-info">No. of Packs Purchased: {{ $customer_words_per_pack->count() }}</p>
        <p class="top-info">Total Sales: $<?php 
            $price_total = 0;
            foreach($customer_words_per_pack as $customer_word){
                $json_note = json_decode($customer_word->note, true);
                $price_total += $json_note['price'];
            }
            echo round($price_total, 2);
        ?>
        </p>
    </div>
    <br>
    <div id="responsive-table">
        <div class="row tbl-wrapper">
            <div class="col s12 outer-tbl"> 
                <table class="striped" id="sorting">
                    <thead>
                        <tr>
                            <th>Date Purchased</th>
                            <th>Word Pack </th>
                            <th>Words </th>
                            <th>Price </th>
                            <th>Customer </th>
                        </tr>
                    </thead>
                    <tbody class="striped">
                        @foreach($customer_words_per_pack as $customer_word)
                        <?php $json_note = json_decode($customer_word->note, true); ?>
                        <tr>
                            <td><?php echo date("M d, Y g:i:s A", strtotime($customer_word->created_at)); ?></td>
                            <td>{{ $pack_selected }}</td>
                            <td>{{ $customer_word->words }}</td>
                            <td><?php echo '$'.round($json_note['price'], 2); ?></td>
                            <td>{{ $customer_word->first_name }} {{ $customer_word->last_name }}</td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <hr class="split">
    @endif
@endforeach

1 Ответ

0 голосов
/ 16 мая 2019

Вы можете использовать двойные кавычки для того же самого,

$pack_title              = $pack->description; // changed this
$customer_words_per_pack = $customer_words->where('note', 'like', "%$pack_title%"); 

Это должно работать

Редактировать

use App\Models\WordPack;
use App\Models\CustomerWord; // make sure they are in Models folder.

Вы должны создатьcustomer_words снова, как следует

$customer_words = CustomerWord::select('customer_emails.first_name', 'customer_emails.last_name', 'words', 'customer_words.created_at', 'note')
            ->join('customer_emails', 'customer_words.customer_id', '=', 'customer_emails.customer_id')
            ->whereNotNull('verified_at');
$pack_title              = $pack->description; // changed this
$customer_words_per_pack = $customer_words->where('note', 'like', "%$pack_title%")->get(); // append get() to close the query 

Это должно работать.

Примечание: Eloquent закроет запрос, как только вы напишите get () в конце.

...