dopcpc9207 2019-05-16 10:02
浏览 88
已采纳

Laravel Eloquent选择查询返回空数组的位置

Right now, i'm using Laravel Eloquent for the retrieval of purchases from a specific pack; supposedly, this line:

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

should return query result objects in an array, instead it returned an empty array. Though, I can retrieve all the pack list using this query:

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

When I create a query that retrieves all the selected pack purchases using:

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

The $pack->description does return a string, but when I place this in the query, it does not return anything.

My goal for this is to retrieve all the purchases from this pack. What could be the most probable cause of this non-returning of results using Laravel Eloquent?

Controller

<?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 = "
";

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

View

@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条回答 默认 最新

  • dphw5101 2019-05-16 10:17
    关注

    You can use double quotes for the same,

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

    It should work

    Edit

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

    You have to create customer_words again as follow

    $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 
    

    It should work.

    Note: Eloquent will close the query once you will write get() at the end.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分